asp.netweb-user-controls

Passing int array as parameter in web user control


I have an int array as a property of a Web User Control. I'd like to set that property inline if possible using the following syntax:

<uc1:mycontrol runat="server" myintarray="1,2,3" />

This will fail at runtime because it will be expecting an actual int array, but a string is being passed instead. I can make myintarray a string and parse it in the setter, but I was wondering if there was a more elegant solution.


Solution

  • Implement a type converter, here is one, warning : quick&dirty, not for production use, etc :

    public class IntArrayConverter : System.ComponentModel.TypeConverter
    {
        public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(string);
        }
        public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            string val = value as string;
            string[] vals = val.Split(',');
            System.Collections.Generic.List<int> ints = new System.Collections.Generic.List<int>();
            foreach (string s in vals)
                ints.Add(Convert.ToInt32(s));
            return ints.ToArray();
        }
    }
    

    and tag the property of your control :

    private int[] ints;
    [TypeConverter(typeof(IntsConverter))]
    public int[] Ints
    {
        get { return this.ints; }
        set { this.ints = value; }
    }