Phil
Phil

Reputation: 4069

ASP.NET C# Creating checkboxes from DataTable

I am new to ASP.NET, but I need to create checkboxes from a query result. So far here is what I have.

In my code behind...I pull the query that I need and then create a DataTable from that result like so:

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;

I then have a class level var defined as

public DataTable dtLocations = new DataTable();

which I populate using the method above in my Page_Load

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

Then in my aspx file (not code behind) I'm doing this to try and create the checkboxes, which needless to say, does not work.

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

Can someone show me how you're supposed to do this in ASP.NET c#? I'll also need to be able to get the value of any that are checked in my code behind when a button on the page is clicked.

When I try using a CheckBoxList like this it tells me I can not use codeblocks here.

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

Upvotes: 0

Views: 365

Answers (1)

VDWWD
VDWWD

Reputation: 35564

You can bind a DataTable directly to a CheckBoxList

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

Upvotes: 1

Related Questions