2014-10-31 66 views
0

我创建5单选按钮,当我的页面加载:asp.net无法访问动态创建的控件

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); 

      } 
     } 
    } 

我想访问他们的另一种方法对应一个点击按钮,但我不能。 :

protected void Button1_Click(object sender, EventArgs e) 
    {    
     RadioButton r = (RadioButton)FindControl("2"); 
     r.Checked = true;    
    } 

当我做我的FindControl方法,我得到以下异常:NullReferenceException异常是未处理的用户代码

+0

但我不明白我如何访问我在page_load方法中创建的单选按钮。 – user2443476 2014-10-31 12:54:20

+0

@SonerGönül这个问题有一个特定的问题。 “如何访问动态控件”。答案应该包含与这个问题有关的细节。您标记为重复的问题不能完全回答问题。 – Shaharyar 2014-10-31 12:58:27

+0

好吧,我重新打开你的问题,因为它不是完全相关的'NullReferenceException'。 – 2014-10-31 12:59:59

回答

1

FindControl没有做深做搜索。您将单选按钮添加到Panel1,但调用的FindControl

RadioButton r = (RadioButton)Panel1.FindControl("2"); 

另一件事。删除if (!Page.IsPostBack)条件。当Button1_Click触发时,页面处于PostBack状态,如果您期望找到它们,则必须创建动态控件。

+0

还有另外一个递归更深的函数,但你不会需要它。我认为伊戈尔有解决方案。 – VRC 2014-10-31 13:04:55

+0

感谢它现在的作品 – user2443476 2014-11-05 10:42:01

2

您已在Panel1中添加了控件,因此您应该在其中找到它。

将行:

RadioButton r = (RadioButton)FindControl("2"); 

有:

RadioButton r = Panel1.FindControl("2") as RadioButton; 
if(r != null) //check for null reference, before accessing 
    r.Checked = true; 
+0

好吧,我也必须删除我的page_load方法中的回发条件是不是? – user2443476 2014-10-31 13:08:25

+0

是的,如果您不希望在回发时丢失控件,则需要将其删除。 – Shaharyar 2014-10-31 13:09:38

+0

感谢它现在的作品 – user2443476 2014-11-05 10:43:07