我試圖用多頁問題創建一個考試。這些問題是在SQL過程中動態創建的。我在我的aspx頁面中有一個Repeater,在我的代碼隱藏中動態創建了一個RadioButtonList。Repeater with RadioButtonList的PagedDataSource
<asp:Repeater ID="ExamQuestionsRepeater" OnItemDataBound="RepeaterItemEventHandler" runat="server">
<ItemTemplate>
<asp:Label ID="QuestionLabel" runat="server"><b><%# Eval("exm_Question") %></b></asp:Label>
<asp:RadioButtonList ID="QuestionsList" runat="server" RepeatDirection="Vertical">
</asp:RadioButtonList>
</ItemTemplate>
<SeparatorTemplate>
<tr>
<td><hr class="ExamQuestionsSeparatorTemplate" /></td>
</tr>
</SeparatorTemplate>
</asp:Repeater>
背後的代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadQuestions();
}
}
private void loadQuestions()
{
DataSet dataSet = getData();
PagedDataSource pagedDS = new PagedDataSource();
pagedDS.DataSource = dataSet.Tables[0].DefaultView;
pagedDS.AllowPaging = true; //indicate that data is paged
pagedDS.PageSize = 10; //number of questions per page
//Edit: I noticed I was setting the page index after I bound the repeater
pagedDS.CurrentPageIndex = CurrentPage;
ExamQuestionsRepeater.DataSource = pagedDS;
ExamQuestionsRepeater.DataBind();
//update previous and next buttons depending on what current page is at
updateButtons();
}
}
我使用OnItemDataBound事件在我的中繼器綁定我的動態單選按鈕列表
protected void RepeaterItemEventHandler(object sender, RepeaterItemEventArgs e)
{
int questionA = 2;
int questionB = 3;
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButtonList questionsRadioButtonList = (RadioButtonList)e.Item.FindControl("QuestionsList");
DataRow row = ((DataRowView)e.Item.DataItem).Row;
if (row.ItemArray[questionA] != null && !String.IsNullOrEmpty(row.ItemArray[questionA].ToString()))
{
ListItem item = new ListItem();
item.Text = row.ItemArray[questionA].ToString();
item.Value = "A";
questionsRadioButtonList.Items.Add(item);
}
if (row.ItemArray[questionB] != null && !String.IsNullOrEmpty(row.ItemArray[questionB].ToString()))
{
ListItem item = new ListItem();
item.Text = row.ItemArray[questionB].ToString();
item.Value = "B";
questionsRadioButtonList.Items.Add(item);
}
}
}
protected void NextButton_Click(object sender, EventArgs e)
{
// Set viewstate variable to the next page
CurrentPage += 1;
// Reload control
loadQuestions();
}
protected void PreviousButton_Click(object sender, EventArgs e)
{
// Set viewstate variable to the previous page
CurrentPage -= 1;
// Reload control
loadQuestions();
}
我的問題是,當我移至下一頁或點擊前一頁,問題列表總是與前10個問題綁定,並且狀態也不存儲在頁面之間。我錯過了什麼,或者在加載下一個「頁面」時需要做些什麼才能加載下10個項目?
編輯:我得到了下一個項目,以正確加載每個頁面。現在問題是我的視圖狀態不會保存每次列表加載時我的單選按鈕的值。當我使用RepeaterItemEventHandler時,我是否覆蓋它?我應該檢查某種方法嗎?
你這是什麼意思是「我的視圖狀態不是每次列表加載時都保存我的單選按鈕的值」?你確定這是實際發生的事情嗎? – jadarnel27
我期望的是,當我點擊上一個和下一個按鈕時,用戶在單選按鈕中選擇的值將在頁面加載之間保存並重新加載。我對這個框架還不熟悉,所以我不確定在分頁數據源時控件狀態的行爲。 –