Bat_Programmer
Bat_Programmer

Reputation: 6851

ASP.NET Radio button checked changed event not firing for first radio button

I am facing an issue where the checked changed event of the first radio button is not firing. I enabled ViewState but still the issue persists. Please see below code:

<span class="pull-right text-right">
    <label class="inline radio">
        <asp:RadioButton runat="server" ID="rdoViewAll" CausesValidation="false" GroupName="Filter" Text="View All" AutoPostBack="true" EnableViewState="true" Checked="true" />
    </label>
    <label class="inline radio">
        <asp:RadioButton runat="server" ID="rdoViewCurrent" CausesValidation="false" GroupName="Filter" Text="View Current" AutoPostBack="true" />
    </label>
    <label class="inline radio">
        <asp:RadioButton runat="server" ID="rdoViewFuture" CausesValidation="false" GroupName="Filter" Text="View Future" AutoPostBack="true" />
    </label>
</span>

And I am setting the checked changed event on Page_Init as below:

public void Page_Init(object sender, EventArgs e)
{
    this.rdoViewAll.CheckedChanged += (s, a) =>
    {
        RebindTerms();
    };
    this.rdoViewFuture.CheckedChanged += (s, a) =>
    {
        RebindTerms();
    };
    this.rdoViewCurrent.CheckedChanged += (s, a) =>
    {
        RebindTerms();
    };
}

One thing I noticed is when I remove the Checked="true" property on the first radio button the CheckedChanged event fires successfully. However, I need the first radio button to be checked by default on page load.

Upvotes: 3

Views: 6241

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73761

You can leave Checked="false" for all the RadioButtons initially, and set the selected button with client code:

private RadioButton selectedRadioButton;

protected void Page_Load(object sender, EventArgs e)
{
    selectedRadioButton = rdoViewAll;

    if (rdoViewCurrent.Checked)
    {
        selectedRadioButton = rdoViewCurrent;
    }

    if (rdoViewFuture.Checked)
    {
        selectedRadioButton = rdoViewFuture;
    }

    rdoViewAll.Checked = false;
    rdoViewCurrent.Checked = false;
    rdoViewFuture.Checked = false;

    ClientScript.RegisterStartupScript(GetType(), "InitRadio", string.Format("document.getElementById('{0}').checked = true;", selectedRadioButton.ClientID), true);
}

Clicking on any RadioButton will always trigger the CheckedChanged event. The RadioButton that is actually selected is stored in selectedRadioButton, if you need it in other parts of the server code.

Upvotes: 3

Related Questions