ASP.NET C#从DataTable创建复选框

时间:2017-12-07 18:58:22

标签: c# asp.net

我是ASP.NET的新手,但我需要从查询结果中创建复选框。到目前为止,这就是我所拥有的。

在我的代码中...我拉出了我需要的查询,然后从那个结果中创建一个DataTable,如下所示:

DataTable dtLocations = new DataTable();
        dtLocations.Columns.Add("ID");
        dtLocations.Columns.Add("VALUE");
        // Pull locations and add to our datatable
        string strConnection = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
        using (SqlConnection dbConn = new SqlConnection(strConnection))
        {
            SqlDataAdapter dbAdapter = new SqlDataAdapter();
            SqlCommand dbCommand = new SqlCommand();
            dbConn.Open();
            dbCommand.CommandText = @"SELECT location_id, location_desc FROM admin_locations WHERE enabled = 'Y'";
            dbCommand.Connection = dbConn;
            SqlDataReader dbReader = dbCommand.ExecuteReader(CommandBehavior.CloseConnection);
            if (dbReader.HasRows) {
                while (dbReader.Read()) {
                    dtLocations.Rows.Add(new object[] { dbReader["location_id"].ToString(), dbReader["location_desc"].ToString() });
                }
            }
        }
        return dtLocations;

然后我将类级别var定义为

public DataTable dtLocations = new DataTable();

我使用上面的方法在我的Page_Load

中填充
protected void Page_Load(object sender, EventArgs e)
{
    if (!(IsPostBack))
    {
        dtLocations = createLocationsDataTable();
    }
}

然后在我的aspx文件中(不是后面的代码)我这样做是为了尝试创建复选框,不用说,它不起作用。

<% foreach (DataRow row in dtLocations.Rows) {%>
                                    <asp:CheckBox ID="idLocationChk" runat="server" Value="<% Response.Write(row["ID"].ToString()); %>" />
                                <% } %>

有人能告诉我你在ASP.NET c#中应该怎么做吗?当点击页面上的按钮时,我还需要能够获得我的代码中检查的任何值的值。

当我尝试使用这样的CheckBoxList时,它告诉我我不能在这里使用代码块。

<asp:CheckBoxList ID="message_locations" runat="server">
                                <% foreach (DataRow row in dtLocations.Rows) {%>
                                    <asp:ListItem>TEST</asp:ListItem>
                                <% } %>
                                </asp:CheckBoxList>

1 个答案:

答案 0 :(得分:1)

您可以将DataTable直接绑定到CheckBoxList

if (!IsPostBack)
{
    CheckBoxList1.DataSource = dtLocations;
    CheckBoxList1.DataTextField = "location_desc";
    CheckBoxList1.DataValueField = "location_id";
    CheckBoxList1.DataBind();
}
相关问题