在DataList中绑定RadiobuttonList

本文关键字:RadiobuttonList 绑定 DataList | 更新日期: 2023-09-27 18:20:20

早上好。在这里发帖之前,我搜索了很多次。我正在做一个类似调查的项目[问答]我可以在数据列表中获得所有问题,现在我正在搜索一种方法,在每个问题的单选按钮列表中显示答案。

这是页面加载

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表和Answer表之间的公共列是Question_id

在DataList中绑定RadiobuttonList

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
        }
    }