我在动态创建的文字控件中找到控件时遇到问题。我希望能够使用fnameID(x)
id获取标签中的值。
ASPX:
<div>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
</div>
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
背后的代码:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 50; i++)
{
CheckBox _checkbox = new CheckBox();
_checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
Panel1.Controls.Add(_checkbox);
Panel1.Controls.Add(new LiteralControl("<Label id='fnameID"
+ i + "' >test" + i + "</Label><br/>"));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label lbl = (Label)Panel1.FindControl("fnameID0");
Response.Write(lbl.Text);
}
目前,当我点击按钮时出现以下错误:
Object reference not set to an instance of an object.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
来源错误:
{
Label lbl = (Label)Page.FindControl("fnameID0");
**Response.Write(lbl.Text);**
}
答案 0 :(得分:2)
尝试明确设置您生成的控件的ID:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 50; i++)
{
CheckBox _checkbox = new CheckBox();
_checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
Panel1.Controls.Add(_checkbox);
LiteralControl dynLabel = new LiteralControl("<Label id='fnameID"
+ i + "' >test" + i + "</Label><br/>");
dynLabel.ID = "fnameID" + i.ToString();
Panel1.Controls.Add(dynLabel);
}
}
您将获得空引用异常,因为找不到具有指定ID的控件,因此FindControl
正在返回null
,并且您无法获得Text
属性null
。