解决方案 »
- C# 连接sql 字符串 (windows验证方式)
- CheckedComboBoxEdit怎么显示多列
- [分享]自己写的一个小程序《个人代码知识库》,含源码,
- 还得麻烦各位帮小弟一个忙
- 求救:一个关于pictureBox的问题!!!!
- 我的winform控件里有子控件,希望设计时点击子控件,属性栏显示对应的依然是父容器?
- 【帮忙看看吧!】好晕啊。
- 关于Remoting 调用的远程对象的2点疑问
- 找错误,高手帮忙解决解决!!!
- 关于DeleteObject的方法的提问
- c#新手,在一个xna模板中看到一个按键函数,看不懂,求前辈指点
- 如何通过程序代码分离EXE和DLL,不借助app.config
像
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的替换原则
不过这样仍然不够优雅,一般这种问题最好是通过改善设计去解决
/// <summary>
/// 根据控件名和属性名赋值
/// </summary>
/// <param name="ClassInstance">控件所在实例</param>
/// <param name="ControlName">控件名</param>
/// <param name="Value">属性值</param>
/// <returns></returns>
public static Object SetValueControlProperty(Object ClassInstance, string ControlName, Object Value)
{
Object ctrl;
Object Result = null;
Type myType = ClassInstance.GetType();
FieldInfo myFieldInfo = myType.GetField(ControlName, BindingFlags.NonPublic | BindingFlags.Instance);
string ComponentTypeName = myFieldInfo.FieldType.Name;
ctrl = myFieldInfo.GetValue(ClassInstance); //取得控件实例
if (myFieldInfo != null && (ComponentTypeName == "DropDownList" || ComponentTypeName == "RadioButtonList"))
{
var listCtrl = ctrl as ListControl;
if (listCtrl != null)
{
bool selected = false;
bool finded = false;
foreach (ListItem it in ((ListControl)listCtrl).Items)
{ if (Value.ToString().Trim().ToLower() == it.Value.ToLower().Trim())
{
finded = true;
it.Selected = true;
break;
}
else
{
it.Selected = false;
}
DropDownList ddl = listCtrl as DropDownList;
RadioButtonList rbl = listCtrl as RadioButtonList;
if ((ddl != null || rbl != null) && selected && it.Selected)//如果是DropDownList则不能多选
{
it.Selected = false;
}
if (finded) selected = true;
}
}
} else if (myFieldInfo != null)
{
var txtCtrl = ctrl as ITextControl;
if (txtCtrl != null) txtCtrl.Text = Value.ToString();
Result = txtCtrl;
}
return Result;
}