我是 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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句