简体   繁体   中英

ASP.NET toggle control visibility from code behind

I have two problems that I'm not sure are related:

I have two DropDownList controls (initially set to not visible) and a RadioButtonList control with autopostback behaviour set to true.

Whenever Postback occurs, I want to read the SelectedValue property from the RadioButtonList control - and depending on that, make one of the DropDownLists visible.

Here's my problem:

1) I can't directly refer to the RadioButtonList control by its ID. The designer.cs file doesn't seem to generate either the RadioButtonList or DropDownList controls. Even if I manually add the controls to the designer.cs file, they are lost upon regenerating. Is this expected behaviour?

2) I tried using the Page.FindControl property in the Page_Load() method.

if(Page.PostBack==true)
{
    RadioButtonList rbl = (RadioButtonList)Page.FindControl("RadioButtonList1");
    if(rbl.SelectedValue=="optionA")
    {
         DropDownList ddA = (DropDownList)Page.FindControl("DropDownListA");
         ddA.Visible = true;   
    }
    else
    {
         DropDownList ddB = (DropDownList)Page.FindControl("DropDownListB");
         ddB.Visible=true;
    }
}

But I'm getting a NullReferenceException at the if condition.

Am I completely on the wrong track? Will someone guide me about the best way to achieve what I want to do?

Also, what can I do to make designer.cs file load the Controls?


EDIT: /facepalm

I figured it out myself. I'd forgotten than I'm using the control inside a table.

Once I moved the Control outside the Table, I could refer to the ID directly.

A lack of sleep and coffee to blame. My apologies. Thank you for the help!

Page.FindControl is not recursive, ie it'll return null if the dropdownlist1 controls is in some other control. check this link for detail and see will you be able to find the dropdownlist correctly.

http://www.mha.dk/post/Recursive-PageFindControl.aspx

You are assigning a value to rb1.SelectedValue and you should check if the control was found.

if(rb1.SelectedValue="optionA") 

should be

if(rb1.SelectedValue != null)
{ 
   if(rb1.SelectedValue == "optionA")
   {
       DropDownList ddA = (DropDownList)Page.FindControl("DropDownListA"); 

       if (ddA != null)
                 ddA.Visible = true;  
   }
} 

If you can't reference the control by its ID, and FindControl fails, it could be that in the aspx file your controls are missing the runat="server" tag.

Is this the case?

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