views:

44

answers:

2

Hi,

So I've got three RadioButtons, They're not in a RadioButtonList because I need to add some textboxes next to each of them.

I've added a GroupName, and on the front end they behave as expected. ONLY ONE appears checked at a time.

However in the code, if I do:

RadioButton1.Checked = true;
RadioButton2.Checked = true;
RadioButton3.Checked = true;

I would expect only the last one, RadioButton3, to be checked, because they all belong to the same group. This is not the case. All three evaluate to true.... how can that be?

I have to set them explicitly to false... am I missing something?

A: 

hi: I test it: this code:(in cs file) protected void Page_Load(object sender, EventArgs e) { RadioButton1.Checked = true; RadioButton2.Checked = true; RadioButton3.Checked = true; } this code(in html) run this program: the result is the radiobutton3 is checked

yapingchen
+1  A: 

I think this is the correct behavior although it is not what you might expect.

Consider that a RadioButton is just a CheckBox with some extended functionality to automatically to give that exclusive checking functionality. In the background it is still a checkbox though. See the hierarchy from MSDN:

System.Object
    System.Web.UI.Control
        System.Web.UI.WebControls.WebControl
            System.Web.UI.WebControls.CheckBox
                System.Web.UI.WebControls.RadioButton

The output has all items with the attribute checked="checked" output for the input of type="radio". Eg:

<input id="rad1" type="radio" name="Test" value="rad1" checked="checked" /><label for="rad1">1</label><br />
<input id="rad2" type="radio" name="Test" value="rad2" checked="checked" /><label for="rad2">2</label><br />
<input id="rad3" type="radio" name="Test" value="rad3" checked="checked" /><label for="rad3">3</label>

From the Checked property documenation:

Checked (inherited from CheckBox): Gets or sets a value indicating whether the CheckBox control is checked.

So the Checked property acts just like the CheckBox version with no functionality included to look for other controls in the same group and remove them which makes sense since it is a singular control.

Kelsey
@Kelsey: thanks a lot for your fast and accurate response mate! That explains why it's behaving in this manner, but I'm surprised that it doesn't honor the GroupName in the back end, when it does in the front end...Maybe I'm using the wrong property... do you think I should be using "Checked" (considering it behaves like a checkbox rather than a radio button - even according to the documentation)? I was expecting to see a property named "Selected" but it doesn't exist.... hmmm.....
Ev
@Ev yes you should be using the checked property but you could easily write a function to mimic the server side behavior at the page level and then just automatically switch everything to false and then set the `RadioButton` you want to checked.
Kelsey