Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ASP.Net, will radio buttons in the same group change Checked state automaticlly?

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!

like image 987
Eric Avatar asked Feb 16 '23 01:02

Eric


2 Answers

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.

like image 119
Mike Christensen Avatar answered May 02 '23 11:05

Mike Christensen


Assign groupname property to both the radiobuttons controls. Radio buttons need to have identical group name property , if not they behave as checkboxes .

like image 32
meghna Avatar answered May 02 '23 10:05

meghna