Skip to main content
 首页 » 编程设计

c#之C# 中的 ComboBox 反射

2024年02月20日9bluestorm

我有这个代码:

typeof(ComboBox).GetProperty("SelectedItem").SetValue("comboBox1", "", null); 

它不起作用。这是错误:

"Object does not match target type"

怎么了?

更新:

我有我的对象的名称(字符串中的组合框。如:

string []s = new s[3]; 
s[0]="comboBox0";  
s[1]="comboBox1";  
s[2]="comboBox2";  

我想将属性 SelectedItem 的值设置到我的组合框 s[i]。我该怎么做?

请您参考如下方法:

SetValue需要有 ComboBox 对象,而不是字符串“comboBox1”。我相信您的应用程序中有一个 ComboxBox 对象,假设:

ComboBox comboBox1 = ....; 

所以你可以调用:

typeof(ComboBox).GetProperty("SelectedItem") 
                .SetValue(comboBox1, "", null); 

如果你使用.NET 4.5,你可以去掉最后的输入:

typeof(ComboBox).GetProperty("SelectedItem") 
                .SetValue(comboBox1, ""); 

编辑:根据您的评论,您不需要使用反射,下面是如果只知道名称就可以获得combox1:

var comboBox1 = Controls.OfType<ComboBox>() 
                      .SingleOrDefault(c => c.Name == "Combobox1"); 
 
comboBox1.SelectedItem = "";