Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Populating a CheckBoxList w/ some items selected

Status
Not open for further replies.

Algernon83

Programmer
Jun 25, 2004
50
US
I was working on a project recently that entailed having a CheckBoxList on a page to represent a number of values. Each of these needed to be checked or unchecked based on an item in the data table used to populate the list. Unfortunately, the only way I could find to do this was the really ugly hack of re-executing the sqlCommand and iterating over the list of rows returned, setting the CheckBox that was generated for that row appropriately. Is there a simpler way to do this?
 
Assuming you have a table with a boolean value to set the CheckBoxList's selected property:
Code:
string strConn = "YourConnectionString";		
SqlConnection conn = new SqlConnection(strConn);
conn.Open();				
string strSql="Select YourLabelValue, YourBooleanValue From YourTable";
SqlCommand cmd = new SqlCommand(strSql,conn);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while(reader.Read())
{
ListItem li = new ListItem();
li.Text = reader["YourLabelValue"].ToString();
li.Value= reader["YourBooleanValue"].ToString();
li.Selected = Convert.ToBoolean(reader["YourBooleanValue"]);
chkLst.Items.Add(li);
}				
conn.Close();
 
If you retrieve all the data on the first run, then you could use a DataView to filter the results (just get the ones you need) and Cache it for PostBacks so you don't need another trip to the DB.

Also, no need to iterate over the rows. You can rig the DataTextField and DataValueField, set the DataSource to the returned results, then call DataBind().
 
Veep, thank you. That's a great suggestion, and I've used that idea. BoulderBum, thanks for hipping me to the DataView class, but using a DataBind doesn't work for what I was doing here. I needed to get values for the ListItem's Vale, Text, and Selected properties from the DB, and DataBind() only gets the first two.
 
Oops. My bad. You're right, there's currently no way to bind to the Checked property.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top