我正在尝试从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();
}
答案 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";