asp.net无法访问动态创建的控件 [英] asp.net cannot access to dynamically created controls
问题描述
我创建5单选按钮,当我的页面加载:
I am creating 5 radio button when my page is loading :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
for (int i = 0; i < 5; i++)
{
RadioButton r = new RadioButton();
r.Text = i.ToString();
r.ID = i.ToString(); ;
Panel1.Controls.Add(r);
}
}
}
我想访问他们的另一种方法对应点击按钮,但我不能。
I would like to access them in another method correspond to a click button, but I cannot. :
protected void Button1_Click(object sender, EventArgs e)
{
RadioButton r = (RadioButton)FindControl("2");
r.Checked = true;
}
当我做我的FindControl方法,我得到以下异常:NullReferenceException异常是由用户code未处理
When I am doing my findcontrol method, I get the following exception : nullreferenceexception was unhandled by user code
推荐答案
的FindControl
并没有做深的搜索。您添加单选按钮面板1
,但调用的FindControl
的页
。
FindControl
does not do deep search. You added radio buttons to Panel1
, but calling FindControl
of Page
.
RadioButton r = (RadioButton)Panel1.FindControl("2");
另一件事。删除如果(!Page.IsPostBack)
状态。当的button1_Click
火灾,页面回发状态,动态控件必须建立,如果你希望找到他们。
Another thing. Remove if (!Page.IsPostBack)
condition. When Button1_Click
fires, the page is in PostBack state and dynamic controls have to be created if you expect to find them.
这篇关于asp.net无法访问动态创建的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!