dynamically created radio buttons

  • Thread starter Thread starter Mike P
  • Start date Start date
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
 
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
 
Thanks Marc, that works perfectly.

I've never really used the 'as' keyword...is this just an alternative
form of casting?
 
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
 
Back
Top