简体   繁体   中英

asp.net cannot access to dynamically created controls

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

When I am doing my findcontrol method, I get the following exception : nullreferenceexception was unhandled by user code

You have added the controls in the Panel1 , so you should find it in there.

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. You added radio buttons to Panel1 , but calling FindControl of Page .

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

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.

You need to check that is controls are created or not and need to check null value. 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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