将列表框项目传递到另一个表单C#上的文本框 [英] pass listbox item to a textbox on another form c#
问题描述
我正在用c#在Visual Studio中制作这个简单的Windows窗体应用程序.我有两种形式.在form1上,我有一个文本框,列表框和两个按钮(一个用于从文本框插入到列表框,另一个用于打开form2).在form2上,我只有一个文本框.我只是想要,当在form1上单击一个按钮(用于打开form2)时,要打开form2,文本框要包含(在formLoad上)来自form1的列表框中的选定项.但是,当我单击按钮时,它说对象引用未设置为对象的实例".我究竟做错了什么?我很确定这很简单,但我做不到.
I am making this simple Windows forms app in Visual studio in c#. I have two forms. On form1 I have a textbox,listbox and two buttons (one to insert into listbox from textbox and another to open form2). On form2 I only have a textbox. I just simply want, when click on a button (for opening form2) on form1, form2 to open and textbox to contain (on formLoad) selected item from listbox from form1. But when I click on button it says "Object reference not set to an instance of an object". What am I doing wrong? I am pretty sure it's something simple but I just can't get it.
提前谢谢!
这是我的代码:
在form1上:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnOpenForm2_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox1.Text);
}
public string Transfer
{
get { return listBox1.SelectedItem.ToString(); }
}
以及在form2上:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Form1 f1 = new Form1();
textBox1.Text = f1.Transfer;
}
推荐答案
因为在Form2_Load
事件中,您总是创建Form1
的新实例,然后访问Transfer
属性,该属性访问的listBox1.SelectedItem
并非为新创建的表单设置.
Because in the Form2_Load
event you always create a new instance of Form1
and then access the Transfer
property which accesses listBox1.SelectedItem
which is not set for the newly created form.
您应该在按钮事件中将裁判移交给表格1:
You should rather pass a referece to form 1 in the button event:
在form1上:
private void btnOpenForm2_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(this);
f2.ShowDialog();
}
以及在form2上:
public partial class Form2 : Form
{
Form1 f1;
public Form2(Form1 f1)
{
this.f1 = f1;
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = this.f1.Transfer;
}
}
这篇关于将列表框项目传递到另一个表单C#上的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!