리플렉션을 사용하여 목록 상자, 콤보 박스, 라디오리스트에 항목을 추가하려고합니다.리플렉션을 사용하여 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로 전송하지 않습니까? 또한 컨트롤을 반환하는 이유는 무엇입니까? 참조 형식이므로이를 수행 할 필요가 없습니다. –
방사성리스트, 드롭 다운 등의 메소드를 사용하고 싶고, 몇 가지 case 문을 사용해야하므로 캔트가 실제로 목록 상자로 캐스팅됩니다. 따라서 반사가 더 좋을 것이라고 생각했습니다. – Peter