(C#+ Windows窗体)在不同的类中添加项目列表框 [英] (c# + windows forms) Adding items to listBox in different class

查看:274
本文介绍了(C#+ Windows窗体)在不同的类中添加项目列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个班(形式),我想从类2 的项目被添加到的ListBox 1级当我点击接受按钮。



我试着用下面的代码,但没有在改变列表框:

 私人无效的button1_Click(对象发件人,EventArgs五)
{
CARRENTAL I =新CARRENTAL ();
字符串ID = idRental.Text.ToString();

i.listBox1.Items.Add(ID);
i.listBox1.Update();
this.Close();
}



在哪里我犯这样的错误?


< DIV CLASS =h2_lin>解决方案

在声明窗体2 RentalId 属性。使用



 :和 CARRENTAL 表(你的第一个表格)做如下(Form2的窗口2 =新Form2的())
{
如果(fomr2.ShowDialog()= DialogResult.OK!)
的回报;

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

实施 Fomr2.RentalId 属性是这样的:

 公共字符串RentalId 
{
{返回idRental.Text; } //你不需要的ToString()调用
}



然后选择你的接受按钮和的DialogResult 属性设置为确定。因此,单击该按钮将关闭您的对话形式,并返回 DialogResult.OK


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.

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. And at CarRental form (your first form) do following:

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

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

Implement Fomr2.RentalId property this way:

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. Thus clicking on that button will close your dialog form and return DialogResult.OK.

这篇关于(C#+ Windows窗体)在不同的类中添加项目列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆