如何利用反射获取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;
DropDownList 反射?属性 反射 属性 方法
/// <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";
else if (ComponentTypeName == "Textbox") PropertyDescriptorName = "Text";
else if (ComponentTypeName == "HiddenField") PropertyDescriptorName = "Value";
PropertyDescriptor myProperty = properties.Find(PropertyDescriptorName, IgnoreCase); //这里设为True就不用区分大小写了
if (myProperty != null)
{
Object ctr;
ctr = myFieldInfo.GetValue(ClassInstance); //取得控件实例
try
{
myProperty.SetValue(ctr, Value);
}
catch (Exception ex)
{
}
}
}
return Result;
}
//执行函数
SetValueControlProperty(this,"dropdownList","9",false)
//其中dropdownList已经绑定好数据源。
[解决办法]
通过名字太不灵活了
像
if (ComponentTypeName == "Label") PropertyDescriptorName = "Text"; else if (ComponentTypeName == "Textbox") PropertyDescriptorName = "Text";
这种判断是否ITextControl
var txtCtrl = ClassInstance as ITextControl;
if(txtCtrol != null) txtCtrol.Text = Value;
连反射都不需要了
而DropDownList或者RadionButtonList判断是否是ListControl
然后通过SelectedValue或者Index赋值就行了,否则别人继承的DropDownList用你的就不行了,违背了OO的替换原则
不过这样仍然不够优雅,一般这种问题最好是通过改善设计去解决