Dynamicly created Radio Buttons

W

Wayne Sepega

I have the following Code:

foreach (MyClass d in myClassCollection)
{
curRadioBtn = new RadioButton();
curRadioBtn.Text = d.ToString();
curRadioBtn.GroupName = "Contact";
curRadioBtn.ID = d.Name;
curRadioBtn.EnableViewState = true;
curRadioBtn.CheckedChanged += RadioButton_CheckedChanged;
curPanel = new Panel();
curPanel.Height = curRadioBtn.Height;
curPanel.Controls.Add(curRadioBtn);
panel1.Controls.Add(curPanel);
}

and I have two other RadioButtons on the form already, they are on Panel1.
The ones on the form cause RadioButton_CheckedChanged to be fired on a post
back, but the dynamiclly created ones don't.

The questions I have are:
1) How do I cause the dynamic radio buttons to fire the event?
2) How do I tell which one is selected, out side of firing the event?
I know I can get the ID in the event from the sender, just curious
on how to do it without the event.
3) When I do the post back all the dynamicly created RadioButtons go away,
how do I force the page to remember them when it's redisplayed without
having to re-create them?

Thanks
Wayne Sepega
 
T

Teemu Keiski

Hi,

there would be answers to those questions, however, have you considered
using easier approach, such as creating them with a Repeater?

Sample (though with textBoxes)
http://forums.asp.net/1158998/ShowPost.aspx

But quick replies:

1. Dynamic controls need to be added on every request and on request
(postback) expecting the events to be raised, they need to be added to
Controls collection at Load event, because postback data loading happens
last time (fixed stage) right after Load.

2. There's not very practical ways. It would need inspecting Request.Form
collection, and locating the control with key there (matching control's
UniqueID), and then getting reference to the instance with Page.FindControl

3. Either with repeater as I demonstrated (Repeater handles control
recreation dirty work), or then just you need to create them on postback,
because postback events won't be raised otherwise.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,830
Latest member
HeleneMull

Latest Threads

Top