我想在form2的form1中向我的组合框添加一个项目。但是,如果我按下按钮,form2将关闭,但该项目不会添加到form1中。我希望你能帮帮我!我在互联网上找不到解决这个问题的方法。
表格2:
public void button5_Click(object sender, EventArgs e)
{
Form1 main = new Form1();
main.AddItem("Item");
this.Close();
}
表格1:
public void AddItem(object item)
{
comboBox1.Items.Add(item);
}
答案 0 :(得分:0)
引用您的' Form1'的名称属性不要创建新实例。然后参考形成组合框控制。
您的原始代码会创建新实例。这意味着它创建了Form1的新版本而没有访问原始版本!
以下代码应该有帮助
public void button5_Click(object sender, EventArgs e)
{
Form1 myForm = whateverYourFormsNamePropertyIs;
myForm.Combobox.AddItem("Item");
this.Close();
}
答案 1 :(得分:0)
首先:您必须将comboBox访问修饰符更改为 public 。然后:
表格2:
public void button5_Click(object sender, EventArgs e)
{
Form1 main = new Form1();
main.AddItem("Item");
this.Hide(); // This will hide Form2 ("this." is redundant)
main.ShowDialog(); // This will show Form1
}
答案 2 :(得分:0)
在form2中......
Form1 f;
public Form2(Form1 parent)
{
InitializeComponent();
f = parent;
}
private void Add_Click(object sender, EventArgs e)
{
f.comboBox1.Items.Add("item");
}
在form1中
public void AddItem(object item)
{
comboBox1.Items.Add(item);
Form2 f = new Form2(this);
f.Show();
}
答案 3 :(得分:0)
原始形式
private void FormPeople_Load(object sender, EventArgs e)
{
populateComboBoxTitles();
}
public void populateComboBoxTitles()
{
comboBox2.Items.Clear();
comboBox2.Items.Add("mr");
comboBox2.Items.Add("miss");
}
private void button5_Click(object sender, EventArgs e)
{
FormAddTitle formAddTitle = new FormAddTitle(this);
formAddTitle.Show();
}
辅助表格
FormPeople formPeople;
public FormAddTitle(FormPeople formPeople)
{
InitializeComponent();
this.formPeople = formPeople;
}
private void button1_Click(object sender, EventArgs e)
{
if (formPeople != null)
formPeople.populateComboBoxTitles();
}