1

我有两种形式:form1 和form 2。comboBox 在form2 中。我正在尝试将一个项目添加到 form1 的组合框选项列表中。这是我到目前为止所尝试的。

form1:          
var form2 = new Form2();                   
if (variable == "value") {           
  form2.Controls["ComboBox1"].Items.Add("another item")          
}

this.Hide();          
form2.Show; 

这个问题是它不允许我选择项目。(它不允许我输入 .Items.Add)


我还尝试通过在表单中​​单击它并将私有更改为公共来公开组合框。这就是我改变它时的样子。

public void comboBox1_SelectedIndexChanged(object sender, EventArgs e){
}

但是当我尝试访问comboBox1所有可用的内容时:

comboBox1_SelectedIndexChanged

form2.comboBox1    //This doesn't work            
form2.comboBox1_SelectedIndexChanged   //This is the only option available 

我可能犯了很多错误,但那是因为我对此很陌生。我刚开始学习,所以如果你能试着简单地解释一下,那会有所帮助。如果可能,请避免 get{} set{} 事情。请向我解释如何以不同的形式公开按钮和其他内容,因为我知道单击它并将私有更改为公开并不是我在上面示例中所做的正确方法。

4

3 回答 3

5

转到可视化 UI 设计器并在属性中找到修饰符并将其更改为 Public: 在此处输入图像描述

现在您需要对代码进行一些小改动:

var form2 = new Form2();                   
if (variable == "value") {           
 form2.ComboBox1.Items.Add("another item");      
}

this.Hide();          
form2.Show; 
于 2014-08-22T19:20:30.613 回答
1

You should write a public method on the Form2 adding items to the combo box on this.

public class Form2 : Form {
    ...

    public void AddItem(object item) {
       comboBox1.Items.Add(item);
    }

    ...
}

That way, you just call that method on Form1.

form2.AddItem(variable);
于 2012-05-21T03:52:13.637 回答
0

it's best to use event handler to do this, you register an event handler in form 1 with the corresponding method when this event handler is called. Then call this event handler in form2. The method will be responsible to add item to the combo box.

于 2012-05-21T03:57:58.940 回答