dynamically created radio buttons

M

Mike P

I am working with some code where a number of contacts are taken from a
table and then added to a page with a radio button to the right of each
one where the name of each radio button has the contact key appended.

RadioButton rbtn = new RadioButton();
rbtn.ID = "btn" +
ds.Tables[0].Rows["ContactKey"].ToString();
rbtn.GroupName = "Group1";

rbtn.CheckedChanged += new
EventHandler(rbtn_CheckedChanged);

if (ds.Tables[0].Rows["PrimaryContact"].ToString() ==
"y")
{
rbtn.Checked = true;
}

pnlContactList.Controls.Add(rbtn);

How in the rbtn_CheckedChanged event do I obtain the Id of the radio
button that is selected?


Cheers,

Mike
 
M

Marc Gravell

You can normally cast the "sender" to the Control (RadioButton in this case)
firing the event; best to do it defensively:

RadioButton rb = sender as RadioButton;
if(rb!=null) { // have a valid RadioButton
// do something with rb
}

Marc
 
M

Mike P

Thanks Marc, that works perfectly.

I've never really used the 'as' keyword...is this just an alternative
form of casting?
 
M

Marc Gravell

The "as" operator returns null if the cast fails (e.g. sender is a TextBox),
where-as a straight cast would throw an exception.

The main reason I started using it is that FxCop kept moaning about
performing the cast twice when following the "test via is, then cast"
approach; "as" covers both of these in one, easily tested, step.

Marc
 

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

Top