CptSupermrkt
CptSupermrkt

Reputation: 7134

De-selecting other radio buttons from another radio button's "CheckedChanged" event

I basically want to achieve what a RadioButtonList does, without using that control (i.e. keep the radio buttons separate.). So I dragged two regular RadioButton (not lists) controls into the page. Both radio buttons are set to AutoPostback=true.

I tried using the following two event handlers:

protected void radio1_CheckedChanged(object sender, EventArgs e)
{
    radio2.Checked = false;
}

protected void radio2_CheckedChanged(object sender, EventArgs e)
{
    radio1.Checked = false;
}

So what I expect is, if radio1 is clicked by the user, radio2 should uncheck. This doesn't happen. There's no error or anything. I stepped through and found that indeed upon selection of one of the radio buttons, the event DOES fire. And it changes the .Checked status of the other radio button to false. However, visually on the page, both radio buttons are still checked. (Seems like a postback issue, I know, but it's not that).


The reason I can't use a RadioButtonList control is that, given other options on the page, I need to disable certain radio button choices. For example, choosing Item A in a dropdown list disables radio1 so it's not even a choice, but choosing Item B again re-enables radio1, and disables radio2.

Upvotes: 2

Views: 4055

Answers (2)

udaya726
udaya726

Reputation: 1018

I just add a check whether the other radio button is checked and it works

 private void radioButton1_CheckedChanged(object sender, EventArgs e)
    {
        if (radioButton1.Checked)
        radioButton2.Checked = false;
    }

    private void radioButton2_CheckedChanged(object sender, EventArgs e)
    {
        if (radioButton2.Checked)
        radioButton1.Checked = false;
    }

Upvotes: 0

vendettamit
vendettamit

Reputation: 14687

You don't need server side event to achieve this. Use GroupName attribute of radiobutton and keep all your radio button under the same groupName Like -

<asp:RadioButton ID="RadioButton1"  GroupName = "a" runat="server" />
<asp:RadioButton ID="RadioButton2" GroupName = "a" runat="server" />
<asp:RadioButton ID="RadioButton3" GroupName = "a"  runat="server" />

Upvotes: 4

Related Questions