我试图将项目添加到使用反射的列表框,组合框,radiolist。我此刻的代码如下:使用反射将项目添加到ListBox,RadioList,Combobox
public static Control ConfigureControl(Control control, ControlConfig ctrlconf)
{
if (control is TextBox)
{
// ...
}
else
{
// get the properties of the control
//
Type controlType = control.GetType();
PropertyInfo[] controlPropertiesArray = controlType.GetProperties();
foreach (PropertyInfo controlProperty in controlPropertiesArray)
{
if (controlProperty.Name == "Items" && controlProperty.PropertyType == typeof(ListItemCollection))
{
object instance = Activator.CreateInstance(controlProperty.PropertyType);
MethodInfo addMethod = controlProperty.PropertyType.GetMethod("Add", new Type[] { typeof(ListItem)});
List<string> popValues = new List<string>(ctrlconf.PopulatedValues.Split(';'));
if (popValues.Count.Equals(0))
{
throw new ArgumentException("No values found for control");
}
else
{
foreach (string val in popValues)
{
addMethod.Invoke(instance, new object[] { new ListItem(val, val) });
}
}
}
}
}
return control;
}
上面的代码填充我已经使用Activator.CreateInstance实例化的listitemcollection,但我不知道如何将它添加到列表框。
任何帮助将是伟大的。
感谢,
彼得
为什么不把控件投到ListBox?另外,为什么你要返回Control - 它是一个引用类型,所以不需要这样做。 – 2009-11-07 22:09:06
无法真正投入列表框,因为我想要使用radiolist,dropdown等方法,并且必须使用几个case语句 - 因此思考反射会更好。 – Peter 2009-11-07 22:12:45