繁体   English   中英

(c# + windows 窗体) 将项目添加到不同类中的 listBox

[英](c# + windows forms) Adding items to listBox in different class

我有两个类(表单),当我单击“接受”按钮时,我希望将class2一个项目添加到class1 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();
}

我在哪里犯了错误?

Form2上声明RentalId属性。 CarRental表格(您的第一个表格)中执行以下操作:

using(Form2 form2 = new Form2())
{
    if (fomr2.ShowDialog() != DialogResult.OK)
        return;

    listBox.Items.Add(form2.RentalId);
}

Fomr2.RentalId这种方式实现Fomr2.RentalId属性:

public string RentalId
{
   get { return idRental.Text; } // you don't need ToString() call
}

然后选择您的“接受”按钮并将其DialogResult属性设置为OK 因此,单击该按钮将关闭您的对话框窗体并返回DialogResult.OK

您创建了一个 CarRental 类型的新实体。 您应该做的是在构造时将第一个表单发送到第二个表单,并通过该实例修改内容。

您需要访问打开的表单而不是创建 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM