0

将值从form2中的文本框发送到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);           
}

它出了什么问题?

4

1 回答 1

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

这只是一个示例,可以查看您的代码有什么问题!

于 2012-09-12T09:01:10.330 回答