[英](c# + windows forms) Adding items to listBox in different class
I have two classes(forms), and I would like an item from class2
to be added to listBox
in class1
when I click "Accept" button.我有两个类(表单),当我单击“接受”按钮时,我希望将class2
一个项目添加到class1
listBox
。
I tried with the following code, but nothing changes in the listBox:我尝试使用以下代码,但列表框中没有任何变化:
private void button1_Click(object sender, EventArgs e)
{
CarRental i = new CarRental();
string id = idRental.Text.ToString();
i.listBox1.Items.Add(id);
i.listBox1.Update();
this.Close();
}
Where did I make the mistake?我在哪里犯了错误?
Declare RentalId
property on Form2
.在Form2
上声明RentalId
属性。 And at CarRental
form (your first form) do following:在CarRental
表格(您的第一个表格)中执行以下操作:
using(Form2 form2 = new Form2())
{
if (fomr2.ShowDialog() != DialogResult.OK)
return;
listBox.Items.Add(form2.RentalId);
}
Implement Fomr2.RentalId
property this way: Fomr2.RentalId
这种方式实现Fomr2.RentalId
属性:
public string RentalId
{
get { return idRental.Text; } // you don't need ToString() call
}
Then select your "Accept" button and set its DialogResult
property to OK
.然后选择您的“接受”按钮并将其DialogResult
属性设置为OK
。 Thus clicking on that button will close your dialog form and return DialogResult.OK
.因此,单击该按钮将关闭您的对话框窗体并返回DialogResult.OK
。
you created a new entity of type CarRental.您创建了一个 CarRental 类型的新实体。 what you should do is to send the first form to the second on construct, and modify things through that instance.您应该做的是在构造时将第一个表单发送到第二个表单,并通过该实例修改内容。
You need to access the open form instead of creating new instance of CarRental form您需要访问打开的表单而不是创建 CarRental 表单的新实例
private void button1_Click(object sender, EventArgs e)
{
CarRental i = (CarRental)Application.OpenForms["CarRentalFormObjectName"];
string id = idRental.Text.ToString();
i.listBox1.Items.Add(id);
i.listBox1.Update();
this.Close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.