开发者

TypeConverter when binding to ASP.NET GridView

I am trying to bind an IList of objects to a GridView's DataSource and one of the properties of the object is an enum. I was trying to use a TypeConverter on the enum to use a Descr开发者_开发百科iption when the object is bound to the GridView Row. It does not look like my EnumConverter.ConvertTo method is being called. Will a TypeConverter be called automatically when the object is being bound to an ASP.NET GridView?

ENUM:

[TypeConverter(typeof(AuditReasonConverter))]
    public enum AuditReason
    {
        [System.ComponentModel.Description("Successful Login")]
        SuccessfulLogin,
        [System.ComponentModel.Description("Failed Login")]
        FailedLogin,
        [System.ComponentModel.Description("New User")]
        NewUser,
        [System.ComponentModel.Description("Edited User")]
        EditedUser
    }

TypeConverter Class:

public class AuditReasonConverter : EnumConverter
    {
        public AuditReasonConverter()
            : base(
                typeof(Blah.Core.AuditItem.AuditReason))
        { }

        public override object ConvertTo(ITypeDescriptorContext context,
            System.Globalization.CultureInfo culture, object value,
            System.Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                return Utilities.GetEnumerationDescription(typeof(Blah.Core.AuditItem.AuditReason), value);  // your code here
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }


No, GridView seems to just go for ToString.

What I have done though is subclass BoundField (or DataControlField = more work) and use your converter in FormatDataValue -

public class ConverterBoundField : BoundField
{
    protected override string FormatDataValue(object dataValue, bool encode)
    {
        TypeConverter converter = TypeDescriptor.GetConverter(dataValue.GetType());
        if (converter.CanConvertTo(typeof(string)))
        {
            return converter.ConvertToString(dataValue);
        }
        return base.FormatDataValue(dataValue, encode);

    }
}

You should probably respect the encode parameter, and do any formatting that was specified... and it is probably best to implement CanConvertTo for your converter also.


I don't think GridView bothers about the TypeConverter attribute when binding for 2 reasons:

  1. It would lower performance in large datasets.
  2. It would make data inconsistent regarding sorting and grouping (datasource says the data was delivered sorted but it does'nt seem sorted because of the converter)

PS: This converter you mentioned would'nt work either anywhere. You must implement "CanConvertTo" method.

PS2: A good approach for doing what you want is to implement a custom cell template.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜