错误:尝试从Form.Controls集合获取控件时对象为null引用

时间:2013-09-05 15:03:39

标签: c# .net winforms

我正在尝试从Label text更改parent Form Child form但我收到此错误Object reference not set to an instance of an object.错误在哪里? 这是我正在使用的代码

private void btnMedicalClgList_Click(object sender, EventArgs e)
        {
            this.ParentForm.Controls["lblMenuItem"].Text = "Medical College List";//getting error here
            ShowMedicalClgList medifrm = new ShowMedicalClgList();
            medifrm.MdiParent = this.ParentForm;
            this.Hide();
            medifrm.Show();           
        }

1 个答案:

答案 0 :(得分:1)

正如我在评论中所说,你不能使用控件的名称作为Controls集合的索引器来获取它,但你可以遍历控件集合找到所需的控件并随心所欲地做任何事情,试试这个:< / p>

Label lbl = null;
foreach (var control in this.ParentForm.Controls)
{
    if (((Control)control).Name == "lblMenuItem")
    {
        lbl = (Label)control;
        break;
    }
}
if (lbl != null)
    lbl.Text = "Medical College List";

或者如果你想写更少的代码:

Control[] foundControls = this.Controls.Find("lblMenuItem", true);
if (foundControls.Any())
    foundControls.First().Text = "Medical College List";