将表单2 文本框中的值发送到form1 中的列表框时,
我收到NullReferenceException
错误。
处理程序代码为:
public void button1_Click(object sender, EventArgs e) {
ListBox LB = Application.OpenForms["Form1"].Controls["Project_list"] as ListBox;
LB.Items.Add(Project_name.Text);
}
它出了什么问题?
答案 0 :(得分:2)
仅用于演示目的... 检查此代码,设置断点并查看会发生什么。
public void button1_Click(object sender, EventArgs e)
{
// i do assume there is a class Form1 within your project?!
Form1 frm = (Form1) Application.OpenForms["Form1"];
// look for Project_list within your Form1.Controls, true to search all childControls too
Control[] ctrls = frm.Controls.Find("Project_list", true);
if (ctrls.Length >0)
{
ListBox LB = ctrls[0] as ListBox;
if (LB!=null)
LB.Items.Add(Project_name.Text);
else
System.Diagnostics.Debug.WriteLine("Doooooh");
}
}
这只是一个示例,可以看到您的代码出了什么问题!