Skip to main content
 首页 » 编程设计

C# 列表框传递字符串

2024年02月20日21lidabo

我似乎在将一些字符串从一种形式传递到另一种形式时遇到了问题。 我在 Form1 上有两个列表框,但我想使用 Form2 将信息传递到 Form1 中的列表框。 在 Form2 中,我有一个 button_Click 函数,它使用参数字符串 a 和字符串 b 调用 Form1 中的函数。

private void button_Click(object sender, EventArgs e){ 
Form1 frm = new Form1(); 
frm.AddItemToListBox(txtBox1.Text,txtBox2.Text); 
} 

下面是调用Form1中AddItemToListBox函数的代码。
以上是Form1中的AddItemToListBox函数。

AddItemToListBox(string a, string b){ 
listBox1.Items.Add(a); 
listBox2.Items.Add(b); 
} 

但是,这不会将字符串添加到列表框中。没有错误信息或任何东西。 我还尝试声明 2 个公共(public)字符串 STR1 和 STR2

AddItemToListBox(string a, string b){ 
listBox1.Items.Add(a); 
listBox2.Items.Add(b); 
STR1 = a; 
STR2 = b; 
} 

但是如果我使用一个按钮来显示 STR1 和 STR2 的值。它们将是 "", String.Empty。显示该值的 MessageBox 中没有显示任何内容。但是,如果我放置 MessageBox.Show(a);和 MessageBox.Show(b);在 AddItemToListBox 函数中,字符串将正确显示,但仍未添加到列表框。

这让我沮丧了大约 2 个小时,我想知道为什么以及如何实际使用该方法将项目添加到列表框(如果可能)。提前致谢。

请您参考如下方法:

尝试在这个方法的末尾添加一个 frm.Show()。

private void button_Click(object sender, EventArgs e) 
{  
    Form1 frm = new Form1();  
    frm.AddItemToListBox(txtBox1.Text,txtBox2.Text);  
    frm.Show(); 
}  

但我确信这不能解决您的问题。只是告诉您需要引用正确的 Form1。我认为您正在创建 Form1 的新实例,您需要解决正确的问题