-1

我正在尝试更改Label textIn parent FormfromChild 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();           
        }
4

1 回答 1

1

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

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";
于 2013-09-05T15:24:20.763 回答