Search code examples
asp.netcustom-server-controls

When can I set default values for properties on server a control?


I have written the following override for the DataFormatString in my BoundField derived control, yet the field is still formatted as a plain number. I assume that this is because the formatting code isn't calling the DataFormatString property but using the private _dataField field. I would like set the base property in my override, but I want to do so based on a declarative FormatType enum property that will determine which default format string to use. Where could I do this?

public override string DataFormatString
{
    get
    {           
        var baseString = base.DataFormatString;
        if (!string.IsNullOrWhiteSpace(baseString))
        {
            return FormatStrings.Currency;
        }
        return baseString;
    }
    set
    {
        base.DataFormatString = value;
    }
}

EDIT: It turns out declarative property values are set when the control is built by it's parent, so it's pretty safe to assume they won't be properly used until after this phase of the page life cycle. This is what I actually wanted to know.


Solution

  • It looks like the parameterless constructor is the best place to do this. I wanted to set some properties to default values based on other properties, but I realised it wasn't necessary if I determined these defaults when needed, versus in the property getters. E.g:

    public BoundReportField()
    {
        _formatType = FieldFormatTypes.String;
    }
    
    protected virtual string GetDefaultFormatString(FieldFormatTypes formatType)
    {
        var prop = typeof(FormatStrings).GetProperty(formatType.ToString()).GetValue(null, null);
        return prop.ToString();
    }
    
    protected virtual IFormatProvider GetFormatProvider(FieldFormatTypes formatType)
    {
        var info = (CultureInfo)CultureInfo.CurrentCulture.Clone();
        info.NumberFormat.CurrencyDecimalDigits = 0;
        info.NumberFormat.CurrencySymbol = "R";
        info.NumberFormat.CurrencyGroupSeparator = ",";
        info.NumberFormat.CurrencyDecimalSeparator = ".";
        return info;
    }
    
    private FieldFormatTypes _formatType;
    public virtual FieldFormatTypes FormatType
    {
        get { return _formatType; }
        set
        {
            _formatType = value;
        }
    }
    
    protected override string FormatDataValue(object dataValue, bool encode)
    {
        var formatString = DataFormatString;
        var formatProvider = GetFormatProvider(_formatType);
        if (string.IsNullOrWhiteSpace(formatString))
        {
            formatString = GetDefaultFormatString(_formatType);
        }
        ApplyFormatStyles(_fieldCell);
        var retString = string.Format(formatProvider, formatString, dataValue);
        return retString;
    }