ASP.NET C#从DataTable创建复选框
我是ASP.NET新手,但我需要根据查询结果创建复选框。到目前为止,这就是我所拥有的 在我的代码隐藏中…我提取我需要的查询,然后根据该结果创建一个DataTable,如下所示:ASP.NET C#从DataTable创建复选框,c#,asp.net,C#,Asp.net,我是ASP.NET新手,但我需要根据查询结果创建复选框。到目前为止,这就是我所拥有的 在我的代码隐藏中…我提取我需要的查询,然后根据该结果创建一个DataTable,如下所示: DataTable dtLocations = new DataTable(); dtLocations.Columns.Add("ID"); dtLocations.Columns.Add("VALUE"); // Pull locations and add to ou
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;
然后我有一个类级别的变量定义为
public DataTable dtLocations = new DataTable();
我在页面加载中使用上面的方法填充它
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#中做到这一点吗?我还需要能够在点击页面上的一个按钮时获取在我的代码中检查的任何值
当我尝试使用这样的复选框列表时,它告诉我这里不能使用代码块
<asp:CheckBoxList ID="message_locations" runat="server">
<% foreach (DataRow row in dtLocations.Rows) {%>
<asp:ListItem>TEST</asp:ListItem>
<% } %>
</asp:CheckBoxList>
试验
您可以将数据表直接绑定到复选框列表
if (!IsPostBack)
{
CheckBoxList1.DataSource = dtLocations;
CheckBoxList1.DataTextField = "location_desc";
CheckBoxList1.DataValueField = "location_id";
CheckBoxList1.DataBind();
}
您可能需要查看复选框列表。@VDWWD-有这样做的好例子吗?我看到了这一点,但它并没有使用ID作为复选框的键值作为标签-它只是所有的文本得到了它。在前面的aspx文件中创建了我的复选框列表,然后创建ListItem并从后面的代码添加到其中。这是实现这一点最直接的方法,但您也可以帮助澄清dtLocations需要首先“加载”,可能是使用CreateLocationsDataable();