简体   繁体   English

asp.net无法访问动态创建的控件

[英]asp.net cannot access to dynamically created controls

I am creating 5 radio button when my page is loading : 我正在加载页面时创建5单选按钮:

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

When I am doing my findcontrol method, I get the following exception : nullreferenceexception was unhandled by user code 当我执行findcontrol方法时,出现以下异常:用户代码未处理nullreferenceexception

You have added the controls in the Panel1 , so you should find it in there. 您已经在Panel1添加了控件,因此应该在其中找到它。

Replace the line: 替换行:

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

with: 与:

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

FindControl does not do deep search. FindControl不会进行深度搜索。 You added radio buttons to Panel1 , but calling FindControl of Page . 您向Panel1添加了单选按钮,但调用了Page FindControl

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

Another thing. 另一件事。 Remove if (!Page.IsPostBack) condition. 删除if (!Page.IsPostBack)条件。 When Button1_Click fires, the page is in PostBack state and dynamic controls have to be created if you expect to find them. Button1_Click触发时,页面处于回发状态,如果希望找到它们,则必须创建动态控件。

You need to check that is controls are created or not and need to check null value. 您需要检查是否已创建控件,并且需要检查null值。 You are doing it a wrong way. 您做错了方法。 To solve this error First check object is initialized or not if it is Initialized that means value is not received by reference variable. 解决此错误的方法首先检查对象是否已初始化(如果已初始化),则意味着引用变量未接收到值。 Please check the following link for reference: http://blog.mastersoftwaresolutions.com/why-null-reference-error-occurred/ 请检查以下链接以供参考: http : //blog.mastersoftwaresolutions.com/why-null-reference-error-occurred/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM