Search code examples
asp.netpostbackdatalistradiobuttonlist

asp.net datalist nested with RadioButtonList on Postback are always NOT SELECTED


I have a asp.net which contains a datalist and inside its itemtemplate it contains a radiobuttonlist

Here is my ASPX code:

<asp:DataList ID="dtlQuestions" runat="server" RepeatDirection="Vertical" DataKeyField="ID" OnItemDataBound="dtlQuestions_ItemDataBound">
    <ItemTemplate>
        <asp:Label ID="q" runat="server" Text='<%# Eval("Question") %>'></asp:Label>
        <asp:RadioButtonList ID="dtlAnswers" runat="server" ValidationGroup='Bla' RepeatDirection="Horizontal" RepeatColumns="5" CssClass="radioButtonList">
        </asp:RadioButtonList>
    </ItemTemplate>
</asp:DataList>

In the code behind, I have a list of "Questons" which each item contains a list of Items. I bind the questions to the Datalist, and each answer inside question is binded to the radioButtonList.

Here is the C# code:

protected void dtlQuestions_ItemDataBound(object sender, DataListItemEventArgs e)
{
    SurveyQuestion drv = e.Item.DataItem as SurveyQuestion;
    RadioButtonList RadioButtonList1 = (RadioButtonList)e.Item.FindControl("dtlAnswers");
    foreach (QuestionAnswer a in drv.QuestionAnswers)
    {
        ListItem i = new ListItem();
        i.Text = a.Answer;
        i.Value = a.Answer;
        RadioButtonList1.Items.Add(i);
    }
}

Now my problem is when on a button click I want to go back and read every radiobutton and see if it is checked or not, I am able to loop through the radiobuttons but all are showing not selected.

Here is the button submit click

protected void btnSubmit_Click(object sender, EventArgs e)
{
    DataList dtlQuestions = Page.FindControl("dtlQuestions") as DataList;

    foreach (DataListItem question in dtlQuestions.Items)
    {
        RadioButtonList rdList = question.FindControl("dtlAnswers") as RadioButtonList;

        foreach (ListItem answer in rdList.Items)
        {
            bool isSelected = answer.Selected;
        }
    }
}

Solution

  • Ohhhh I found it out. on Page_Loadi was adding a List of questons to the DataSource of the DataList. My problem was I hadn't add a if(!Page.IsPostBack) to that part, so each time the button was clicked it was rebinding the data and losing my selected values. :)