Posted By: object88 | Sep 23rd, 2004 @ 7:31 PM
page 1 of 1
Comments: 3 | Views: 7863
object88
object88
amplify.
Maybe I'm hallucinating, but in the Win32 world, wasn't there a way to access a group of RadioButtons?  So you could do something like:

RadioButton checkedButton = myRadioButtonGroup.SelectedButton;

or something?

Is there any way to do that in .Net?  I have a collection of 16 radio buttons, and I need to programmatically select 1... and at the moment, I've got this stupid-long switch statement calling out each radio button individually if it's to be selected.  I.e.:

RadioButton checkedButton;
if (myRadioButton1.Checked)
{
   checkedButton = myRadioButton1;
}
else if (myRadioButton2.Checked)
{
   checkedButton = myRadioButton2;
}
...
else
{
   checkedButton = myRadioButton16;
}


That just seems silly.


If it was *me* I would change your method..


Add an event to all your RadioButtons pointing to the same event handler like this:

this.radioButton1.CheckedChanged += new System.EventHandler(checkedBox);

this.radioButton2.CheckedChanged += new System.EventHandler(checkedBox);

// ---------------------------

public void checkedBox(object x, System.EventArgs y)

{

MessageBox.Show(((RadioButton)x).Checked.ToString());

}



Assuming you don't want a quick and dirty solution - you could also loop though the form controls collection. You have to figure that one out on your own though. Smiley

Manip wrote:

Assuming you don't want a quick and dirty solution - you could also loop though the form controls collection. You have to figure that one out on your own though. Smiley


Hmm, I'm not sure If i Would call it dirty...  Personally I like the looping better because its more extensible, If i ever add/remove controls at either design time or run time I dont have to wory about handlers. 

Here is how I would probably do it:

Dim ctrl As Control
Dim rdo As RadioButton
For Each ctrl In Me.Controls
   If TypeOf ctrl Is RadioButton Then
      rdo = CType(ctrl, RadioButton)
      If rdo.Checked Then
         MessageBox.Show(rdo.Text)
      End If
   End If
Next

Then again, events would be a fun way to do it.  Great. Now I'm all conflicted.  I suppose in the end the event based model would be slightly faster, especially on a form that is heavy with controls.


In any case, now you have two ways of solving your questio.

page 1 of 1
Comments: 3 | Views: 7863