0

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

user2443476
  • 1,835
  • 7
  • 32
  • 57
  • But I don't understand how I can access to my radio buttons created in page_load method. – user2443476 Oct 31 '14 at 12:54
  • @SonerGönül The question has a specific problem. "How to access dynamic controls". The answer should contain the details related to this problem. The question you marked as duplicate doesn't completely answer the question. – Shaharyar Oct 31 '14 at 12:58
  • Ok, I reopened your question since it is not entirely related to `NullReferenceException`. – Soner Gönül Oct 31 '14 at 12:59
  • If you ONLY create the controls on non-postback, they won't be available during a postback. – Zeph Oct 31 '14 at 13:11

3 Answers3

2

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;
Shaharyar
  • 11,393
  • 3
  • 39
  • 59
1

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.

Igor
  • 15,444
  • 1
  • 22
  • 29
  • There is another function that goes deeper recursively but you wont need that. I think that Igor has the solution. – VRC Oct 31 '14 at 13:04
0

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/

Ravi Garg
  • 492
  • 3
  • 5