2

I have a situation where I have a page in ASP.NET. In this page I have a RadioButtonList, which contains 5 solutions to a question. The RadioButtonList is feeded by an object, which has these solutions.

I have a timer, which runs every second, to update loads of graphical controls. Everything works, BESIDES the RadioButtonList selection.

This is what happends:

When I select an item in the RadioButtonList and the timer tick, the selectedIndex of the RadioButtonLIst value is 0.

This means it selects the FIRST item in the list. However, IF I click an item, which has a "Yes" value in it (the value field can either have "No" or "Yes", it will stay at this item.

First of all, I have NO idea why the timer re-select my RadioButtonList selection, as any other Page_Load event does nothing. And even if that makes sense, I have no idea why it just re-selects SOME of the answers..

I have the following HTML code:

<asp:Timer ID="AssignmentTimer" runat="server" Interval="1000">
</asp:Timer>


<asp:UpdatePanel ID="FightUpdatePnl" runat="server" UpdateMode="Always" ChildrenAsTriggers="True">
   <Triggers>
      <asp:AsyncPostBackTrigger ControlID="AssignmentTimer" EventName="Tick"/>
   </Triggers>

   <ContentTemplate>
      <asp:Panel ID="AssignmentDiv" runat="server" CssClass="FightDiv">
      </asp:Panel>
   </ContentTemplate>
</asp:UpdatePanel>

I have the following code behind:

protected void Page_Load(object sender, EventArgs e)
{
    SetupPage();
}

private void SetupPage()
{
   RadioButtonList list = new RadioButtonList();

   list.DataSource = question.PossibleSolution;
   list.DataTextField = "Content";
   list.DataValueField = "IsAnswer";
   list.DataBind();

   AssignmentDiv.Controls.Add(list);
}

So, to summarize, my problem is...

When the timer ticks, the RadioButtonList re-select item 0. This is however not consistent, and sometimes it doesn't re-select. I'd rather it didn't re-select at all! :)

4

1 回答 1

0

我不确定是否没有其他可能的原因,但您不应将 RadioButtonList 绑定在 Page_Load on postbacks中。否则选择会丢失。

if (!IsPostBack) {
   SetupPage();
}

仅当页面首次加载并更改其数据源时才执行此操作(在更新问题的事件处理程序中)。

  • 您正在将 RadioButtonList 动态添加到页面。好的,这必须在每次回发时完成(如果可能,在 Page_Init 中)。但它不需要在每个 Postback 上重新绑定到数据源,因为 Viewstate 会在 Postbacks 上保存选择。因此,从 RadioButtonList.DataBind 中拆分(重新)创建和添加 RadioButtonList。第一个必须在每次回发时完成,第二个仅在第一次加载和源更改时(在事件处理程序中)。
  • 设置 RadiobuttonList 的 ID。否则回发后不会加载 ViewState。ID 应该是唯一的。如果您要添加多个 RadioButtonList,请使用计数器或类似的东西。
于 2010-11-16T18:17:10.113 回答