日期:2014-05-17  浏览次数:20815 次

如何利用反射获取DropDownList控件的Items属性的FindByValue方法
本帖最后由 lll029 于 2013-07-22 23:11:13 编辑
想做一个通用反射,根据控件名,将一个值赋到该控件的指定属性中。
例如:
如果是Textbox或Label,则把值赋到Text中,
如果是HiddenField,则把值赋到Value中。
以上已能实现,现在碰到的问题是DropDownList控件。
我想实现判断将该值所在的Item设置为Selected,正常情况下我要将其中的某一个Item赋为Selected,我可以如下写:

ListItem item = dropdownList.Items.FindByValue("9");
item.Selected = true;


请教各位大仙,现在我想利用反射将这个方法通用化,该怎么实现哦?
附该函数:

    /// <summary>
    /// 根据控件名和属性名赋值
    /// </summary>
    /// <param name="ClassInstance">控件所在实例</param>
    /// <param name="ControlName">控件名</param>
    /// <param name="Value">属性值</param>
    /// <param name="IgnoreCase">属否不区分大小写,false区分,true区分</param>
    /// <returns></returns>
    public static Object SetValueControlProperty(Object ClassInstance, string ControlName, Object Value, bool IgnoreCase)
    {
        Object Result = null;
        Type myType = ClassInstance.GetType();
        FieldInfo myFieldInfo = myType.GetField(ControlName, BindingFlags.NonPublic | BindingFlags.Instance);
        string ComponentTypeName = myFieldInfo.FieldType.Name;
        if(myFieldInfo != null && ComponentTypeName=="DropDownList")
        {
           //DropDownList控件,怎么写哦?
        }

        else if (myFieldInfo != null)
        {
            
             //以下是Label、Textbox、HiddenField,已能实现。
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(myFieldInfo.FieldType);
            string PropertyDescriptorName="";
            if (ComponentTypeName == "Label") PropertyDescriptorName = "Text";