Sams
Sams

Reputation: 21

SelectedItem changes on postback for Dynamically loaded Radiobuttonlist

I have the Radiobuttoncontrol definition static in the design page but loading the contents dynamically from db. But whenever i do postback, my selection vanishes and the first dynamic item is selected by default

for instance if i have 3 items Test1 Test2 Test3

and i select Test2 and click on Button to postback. Page reloads with Test1 selected

Can you please check whats wrong here

<body>
    <form id="form1" runat="server">
        <asp:Literal ID="ltlQues" runat="server"></asp:Literal>
            <asp:RadioButtonList ID="RadioButtonList1" runat="server" Height="32px" Width="334px">
                <asp:ListItem>Test1</asp:ListItem>
                <asp:ListItem>Test2</asp:ListItem>
                <asp:ListItem>Test3</asp:ListItem>
            </asp:RadioButtonList>
        <asp:Button ID="Button1" runat="server" Text="Vote" BorderStyle="Groove" OnClick="Button1_Click" Height="26px" Width="60px" />
        <asp:HiddenField ID="QuestionId" runat="server" />
    </form>
</body>
/// <summary>
/// For page load
/// </summary>
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Session["userid"] = "123";
        loadPoll();
    }
}

/// <summary>
/// to load Active Poll
/// </summary>
private void loadPoll()
{
    try
    {
        ListItem li;
        SqlDataAdapter adaQuestionAndAnswers = dbObj.getAdapter("SelectQuestion");
        DataSet dsResults = new DataSet();
        adaQuestionAndAnswers.Fill(dsResults);

        
        bool isQuesionDataFilled = false;
        DataTable dt = dsResults.Tables[0];
        foreach (DataRow row in dt.Rows)
        {
            if (!isQuesionDataFilled)
            {
                    ltlQues.Text = row["QuestionText"].ToString();
                    QuestionId.Value = row["QuestionID"].ToString();
                    //ltlQuesOther.Text = row["AnswerText"].ToString();
                    //ltlvotecount.Text ="Total "+row["total"].ToString()+" Votes";
                    isQuesionDataFilled = true;
            }
            //add answers to RadioButtonList
            li = new ListItem();
            li.Text = row["AnswerText"].ToString();
            li.Value = row["QuestionID"].ToString();
            li.Attributes.Add("group", "contestants");
            RadioButtonList1.Items.Add(li);
        }
    }
    catch (Exception ex)
    {
        //Log the error
        Response.Write(ex.Message);
    }
}

//To Vote
protected void Button1_Click(object sender, EventArgs e)
{
    try
    {
        Response.Write(RadioButtonList1.SelectedItem.Text);
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
}

Upvotes: 2

Views: 31

Answers (0)

Related Questions