DataList中绑定RadiobuttonList

问题描述:

早上好。 我在这里张贴之前多次搜索。 我正在调查一个项目[问题与解答] 我能够在datalist中获得所有问题,现在我正在寻找一种方法来在每个问题内的单选按钮列表中显示答案。DataList中绑定RadiobuttonList

这里是页面加载

protected void Page_Load(object sender, EventArgs e) 
    { 
     string CS = ConfigurationManager.ConnectionStrings["TMConnectionString"].ConnectionString; 
     SqlConnection con = new SqlConnection(CS); 

     //Getting All Questions 

     SqlDataAdapter dr = new SqlDataAdapter("select * from Question ", con); 
     DataSet ds = new DataSet(); 
     dr.Fill(ds, "Qs"); 
     OuterDataList.DataSource = ds.Tables["Qs"]; 
     OuterDataList.DataBind(); 
    } 

这里是页面主体

<body> 
<form id="form1" runat="server"> 
<h1>Test Page</h1> 
    <asp:DataList ID="OuterDataList" RunAt="server"> 
    <ItemTemplate> 
     <h4><%# DataBinder.Eval (Container.DataItem, "Question") %></h4> 
     <asp:RadioButtonList ID="RadioButtonList1" runat="server"></asp:RadioButtonList> 
    </ItemTemplate> 
    </asp:DataList> 
</form> 

我不知道如何绑定单选按钮列表和群组的答案。 注意:问题表和答案表之间的公共列是Question_id

+0

您是显示答案还是试图让用户记录他们的答案?表“Qs”是否包含一个具有位值的列? – 2014-09-01 23:58:17

+0

对不起Trevor,我不明白你的意思。 但是看看,Qs表只有[Qid,Question] 我将根据问题ID使另一个SQLDATAAdapter从Answer表中获取数据。 – Bassem 2014-09-02 00:03:54

Firt将制作如下的模板。

<asp:DataList runat="server" ID="DataList1" RepeatDirection="Vertical" 
DataKeyField="QuestionID" onitemdatabound="DataList1_ItemDataBound"> 
<ItemTemplate> 
    <table> 
     <tr> 
      <td> 
       <%# Eval("Question") %> 
      </td> 
     </tr> 
     <tr> 
      <td> 
       <asp:RadioButtonList runat="server" ID="RadioButtonList1"> 
       </asp:RadioButtonList> 
      </td> 
     </tr> 
    </table> 
</ItemTemplate> 

,使用DataList1_ItemDataBound后,你可以绑定你的答案。

protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e) 
    { 
     if (e.Item.ItemType == ListItemType.Item) 
     { 
      RadioButtonList RadioButtonList1 = (RadioButtonList)e.Item.FindControl("RadioButtonList1"); 
      //Get questionID here 
      int QuestionID = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "QuestionID")); 
      //pass Question ID to your DB and get all available options for the question 
      //Bind the RadiobUttonList here 
     } 

    } 
+0

1000000000谢谢seminda :),它的工作原理 ,但我们必须添加e.Item.ItemType == ListItemType.AlternatingItem也显示所有问题的答案 谢谢:) – Bassem 2014-09-02 00:29:00