代码隐藏获取错误的RadioButton值

时间:2012-09-10 10:47:41

标签: radio-button webforms

就像我在标题中写的那样,当我尝试更改RadioButton的选择时,代码隐藏会得到错误的值。

Dilemma.aspx:

<asp:RadioButtonList ID="rbList" runat="server">
    <asp:ListItem Text="Yes, please." />
    <asp:ListItem Text="No, thanks." />
    <asp:ListItem Text="Ummm... maybe." />
</asp:RadioButtonList>
<asp:Button ID=""btnChoose" runat="server" text="OK" OnClick="btnChoose_Click" />

Dilemma.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    int initialIndex = GetInitialIndex(); // Simplified for sake of question.
    rbList.SelectedIndex = initialIndex; // This works.
}

protected void btnChoose_Click(object sender, EventArgs e)
{
    int selection = rbList.SelectedIndex; // This gets it wrong!
}

代码隐藏仍然认为所选索引是初始索引,而不是获得新选择的RadioButton。

为什么?

1 个答案:

答案 0 :(得分:0)

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        int initialIndex = GetInitialIndex(); // Simplified for sake of question.
        rbList.SelectedIndex = initialIndex; // This works.
    }
}

有人发布了这个答案,但由于某种原因将其删除了 无论是谁在我面前发布了这个答案 - 它都有效!