![](/img/trans.png)
[英]How do I get the RadioButtonList_SelectedIndexChanged event handler to execute after the first execution of that event in asp.net C#?
[英]Get SelectedValue of RadioButtonList on SelectedIndexChanged event in a datalist using C#
我創建了一個DataList
,其中有2個Label
和一個RadioButtonList
。 2 Label
包含問題ID和隱藏了問題ID的問題,而RadioButtonList
包含選項。 所有這些控件都是有界的。 這是代碼:
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<asp:Label ID="Que_id" Visible="false" runat="server" Text='<%# Eval("question_id") %>'></asp:Label>
<asp:Label ID="Question" runat="server" Text='<%# Eval("question") %>'></asp:Label>
<asp:RadioButtonList ID="RadioButtonList1" AutoPostBack="true" RepeatColumns="2" runat="server" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
</ItemTemplate>
</asp:DataList>
我想做的是每當用戶在RadioButtonList
選擇一個選項時,所選選項及其問題ID都應存儲在數據庫中。 在按鈕單擊事件中存儲整個DataList
很容易,但是當用戶選擇特定問題的選項時,我想並排存儲響應。
我不知道如何獲得的問題ID SelectedIndexChanged
事件,但我想在下面的代碼SelectedIndexChanged
獲得選擇的選項值,但是這也不能正常工作。
RadioButtonList rbl = (RadioButtonList)DataList1.FindControl("RadioButtonList1");
string answer=rbl.SelectedValue;
為了進一步說明,我將這些數據從數據庫引入了數據DataSet
,並針對問題ID,問題和選項進行了過濾。 這些值是在Page_Load期間在if(!IsPostBack)中設置的。
試試下面,
修改
<asp:DataList ID="DataList1" runat="server">
至
<asp:DataList ID="DataList1" OnItemCommand="DataList1_command" runat="server">
假設您有一個<asp:Button
和id為button1
而OnClick為bclick
void bclick(object sender, DataListCommandEventArgs e)
{
foreach (DataListItem item in DataList1.Items)
{
HtmlInputRadioButton radio = (item.FindControl("radioButton") as HtmlInputRadioButton);
if (radio.Checked)
{
// this is you checked radio
}
}
}
您可以使用HiddenField將問題ID存儲在DataList中(它比不可見的Label更“自然”):
<asp:HiddenField ID="hiddenQuestionID" runat="server" Value='<%# Eval("question_id") %>' />
在RadioButtonList的事件處理程序中,可以使用sender
參數來檢索控件,然后獲取選定的值。 RadioButtonList的NamingContainer
還包含HiddenField,從中可以獲取問題ID:
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList rbl = sender as RadioButtonList;
string answer = rbl.SelectedValue;
HiddenField hiddenQuestionID = rbl.NamingContainer.FindControl("hiddenQuestionID") as HiddenField;
string questionID = hiddenQuestionID.Value;
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.