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

5

本文介绍了(c# + windows forms) 将项目添加到不同类的listBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有两个类(表单),我希望在单击时将 class2 中的一个项目添加到 class1 中的 listBox接受"按钮.

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();
}

我在哪里犯错了?

推荐答案

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

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);
}

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

Implement Fomr2.RentalId property this way:

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

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

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 forms) 将项目添加到不同类的listBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14