[英]ASP.NET C# Creating checkboxes from DataTable
我是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>
您可以将DataTable直接绑定到CheckBoxList
if (!IsPostBack)
{
CheckBoxList1.DataSource = dtLocations;
CheckBoxList1.DataTextField = "location_desc";
CheckBoxList1.DataValueField = "location_id";
CheckBoxList1.DataBind();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.