Search code examples
c#asp.netpostbackradiobuttonlist

Incoherent postback behavior with radio button list selection


I have a:

  • RadioButtonList with a selection by default for the first item.

  • LinkButton to unselect this choice.

  • LinkButton to display the index of the RadioButtonList

If I click on the Unselect and then on Save, Index 0 for the first item is displayed. This seemingly wrong behavior is caused by the postback that reloads the page and selects according to the default setting.

BUT: If I now choose Item2 of the List and then click on save, I would expect the same behavior with the postback resetting the RadioButtonList to it's initial values. But Index 1 for List-Item2 is displayed.

So "not-Selected" is overruled on postback, while "selected" is not! Is that really that way? Confusing and hard to handle.

    <asp:RadioButtonList ID="RBL_SelectType" runat="server">
        <asp:ListItem Text="Choice1" Value="0" Selected="True" />
        <asp:ListItem Text="Choice2" Value="1" />
    </asp:RadioButtonList>

    <asp:LinkButton ID="LB_Reset" runat="server" OnClick="Unselect">unselect RBL</asp:LinkButton>
    <asp:LinkButton ID="LB_Save" runat="server" OnClick="Save">Save</asp:LinkButton>

    <asp:Label runat="Server" ID="Message" />

with:

    protected void Save(object sender, EventArgs e)
    {
        Message.Text = "Index = " + Convert.ToString(RBL_SelectType.SelectedIndex);
    }

    protected void Unselect(object sender, EventArgs e)
    {
        RBL_RBL_SelectType.SelectedIndex = -1;
    }

Solution

  • This is a solution to the problem that I had, although it does not explain the behavior that in my eyes keeps being incoherent; I hoped to receive more feedback or confirmation from other users of this behavior.

    So, whenever you need to set the default selection for a RadioButtonList, DON'T do it in the markup as it will loose the selection "nothing selected" after a postback, BUT do it in the code behind on page_load.

    protected void Page_Load(object sender, EventArgs e)
    {
       if (!Page.IsPostBack)
       {
           RBL_SelectType.SelectedIndex = 0;
       }