tags:

views:

48

answers:

3

Hello, I have a Asp page containing 2 radio buttons and other textbox and labels. The things is that I have to make some of them disapear (not visible) when a radio button is selected.

I thought about using a ControlCollection and adding the control I need to make invisible to it. But as soon as I had them to the ControlCollection, they disapear from my web page. I have no idea why.

C# code :

private void createGroup()
{
    ControlCollection cc = CreateControlCollection();
    cc.Add(txt1);
    cc.Add(txt2);
    // and so on...
}

If I call this function on the Page_Load() event, no control are on the page.

Thanks

A: 

Dynamic controls should be created in the PreInit event. Read about ASP.NET page lifecycle.

Darin Dimitrov
The controls are already on the page, I only want some kind of collection to iterate over them.
Frank
Doesn't `this.Controls` collection help?
Darin Dimitrov
+2  A: 

Have you tried simply setting Visible=false for each control in the radio button selection handler?

  void YourRadioButton_CheckChanged(Object sender, EventArgs e) 
  {

     txt1.Visible = !YourRadioButton.Checked;
     txt2.Visible = !YourRadioButton.Checked;
     // and so on... 
  }

If you want to create collections of controls in your page load to ease manipulation, just create a List<WebControl>.

List<WebControl> yourControls = new List<WebControl>();
//...

protected void Page_Load(object sender, EventArgs e)
{
    yourControls.Add(txt1);
    yourControls.Add(txt2);
    // and so on... 
}
jball
Yes. This works, but there is a lot of them. That's why I want to have some kind of collection of controls so I can do a foreach over the collection.
Frank
I see. I've added a solution for that.
jball
Thank you for your help. Find out that there was a Panel object that would make invisible everything it contains if you set it visible property to false.
Frank
+1  A: 

The Page object already has a collection of controls called Controls. You could do something like this:

  void YourRadioButton_CheckChanged(Object sender, EventArgs e) 
  {
     foreach(Control control in this.Controls)
     {
         if(control is Textbox)
         {
             // do something
         }
     }
  }
KevnRoberts