There are 2 radio buttons in the same group on the page:
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="Group1"/>
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="Group1"/>
In the code behined, I write the code to check both radio buttons:
RadioButton1.Checked = true;
RadioButton2.Checked = true;
I thought the RadioButton1.Checked
will be false
because they are in the same group, when I check the second one, the first one will automaticlly uncheck. But actually, they are both Checked=true
.
In my application, there is a switch-case like this:
// Some code to check the default RadioButton
switch(val){
case 1:
RadioButton1.Checked = true;
case 2:
RadioButton2.Checked = true;
}
So sometimes both radio buttons' Checked
will be true. That's odd, so I changed the code to:
switch(val){
case 1:
RadioButton1.Checked = true;
RadioButton2.Checked = false;
case 2:
RadioButton1.Checked = false;
RadioButton2.Checked = true;
}
This works fine but what if I need add 10 more radio buttons, write a long list of =true, =false .....?
Any ideas? Thanks!
Rather than a switch
statement, you'd probably be better off with:
RadioButton1.Checked = (val == 1);
RadioButton2.Checked = (val == 2);
RadioButton3.Checked = (val == 3);
// and so on ...
RadioButton10.Checked = (val == 10);
This way, everything gets set to false
except for the RadioButton
equal to val
. If you had a huge amount of RadioButton
controls, maybe you'd want to put them in an array and loop through that instead.
Assign groupname property to both the radiobuttons controls. Radio buttons need to have identical group name property , if not they behave as checkboxes .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With