I'm working on a Winforms app and I have 5 radio buttons. I need to know which one is checked. Is there a better/more compact way of doing this in C#?
For now I have this:
if (rbtnArgent.Checked)
return "Silver";
else if (rbtnBleuF.Checked)
return "Dark Blue";
else if (rbtnBleuP.Checked)
return "Light Blue";
else if (rbtnJaune.Checked)
return "Yellow";
else
return "Pink";
It's working but maybe i will need to add more radio buttons to my form in the future...
CodePudding user response:
You might want to check out Microsoft's RadioButton docs. Their solution is to handle the RadioButtons
being clicked in events, and keep track of the currently active one.
That would give you:
// Reference to current radiobutton
RadioButton selectedrb;
// Register event handlers for all your radio buttons
rbtnArgent.CheckedChanged = new EventHandler(radioButton_CheckedChanged);
rbtnBleuF.CheckedChanged = new EventHandler(radioButton_CheckedChanged);
// ... (You could also do this in a loop if you were to have a lot of radiobuttons)
void radioButton_CheckedChanged(object sender, EventArgs e) {
RadioButton rb = sender as RadioButton;
if (rb == null) {
MessageBox.Show("Sender is not a RadioButton");
return;
}
// Ensure that the RadioButton.Checked property
// changed to true.
if (rb.Checked) {
// Keep track of the selected RadioButton by saving a reference to it
selectedrb = rb;
}
}
// When you want to check the radiobutton, just compare against the value of selectedrb
CodePudding user response:
I guess your RadionButtons are placed on a GroupBox
to ensure that only one can be selected, right? Anyway, you can use a Dictionary(Of RadioButton, string)
for the color mapping. Initialize it in the Form_Load
event
private ColorMapping As Dictionary(Of RadioButton, string)
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
ColorMapping = new Dictionary(Of RadioButton, string)()
ColorMapping.Add(rbtnArgent, "Silver")
' ... '
End Sub
With the GroupBox
-container you can get the color in this way:
Dim checkedRB = ColorGroupBox.Controls.OfType(Of RadioButton).FirstOrDefault(Function(rb) rb.Checked)
Dim chosenColor = If(checkedRB Is Nothing, Nothing, ColorMapping(checkedRB))
chosenColor
is the color-string that you want. It's basically a 2-liner.
You don't need the GroupBox
for the Dictionary
-approach, but it is good practise to place dependent RadioButtons on one. If you don't have one you can use the same approach but replace ColorGroupBox
in ColorGroupBox.Controls.OfType(Of RadioButton)
with the container control the RadioButtons are placed in(if there's none use Me.Controls....
).