Passing int array as parameter in web user control

2019-01-17 20:10发布

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.

10条回答
不美不萌又怎样
2楼-- · 2019-01-17 20:59

Great snippet @mathieu. I needed to use this for converting longs, but rather than making a LongArrayConverter, I wrote up a version that uses Generics.

public class ArrayConverter<T> : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        string val = value as string;
        if (string.IsNullOrEmpty(val))
            return new T[0];

        string[] vals = val.Split(',');
        List<T> items = new List<T>();
        Type type = typeof(T);
        foreach (string s in vals)
        {
            T item = (T)Convert.ChangeType(s, type);
            items.Add(item);
        }
        return items.ToArray();
    }
}

This version should work with any type that is convertible from string.

[TypeConverter(typeof(ArrayConverter<int>))]
public int[] Ints { get; set; }

[TypeConverter(typeof(ArrayConverter<long>))]
public long[] Longs { get; set; }

[TypeConverter(typeof(ArrayConverter<DateTime))]
public DateTime[] DateTimes { get; set; }
查看更多
Animai°情兽
3楼-- · 2019-01-17 21:02

Do do what Bill was talking about with the list you just need to create a List property on your user control. Then you can implement it as Bill described.

查看更多
地球回转人心会变
4楼-- · 2019-01-17 21:06

You could add to the page events inside the aspx something like this:

<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
    YourUserControlID.myintarray = new Int32[] { 1, 2, 3 };
}
</script>
查看更多
Viruses.
5楼-- · 2019-01-17 21:10

To add child elements that make your list you need to have your control setup a certain way:

[ParseChildren(true, "Actions")]
[PersistChildren(false)]
[ToolboxData("<{0}:PageActionManager runat=\"server\" ></PageActionManager>")]
[NonVisualControl]
public class PageActionManager : Control
{

The Actions above is the name of the cproperty the child elements will be in. I use an ArrayList, as I have not testing anything else with it.:

        private ArrayList _actions = new ArrayList();
    public ArrayList Actions
    {
        get
        {
            return _actions;
        }
    }

when your contorl is initialized it will have the values of the child elements. Those you can make a mini class that just holds ints.

查看更多
登录 后发表回答