Click to See Complete Forum and Search --> : repopulating CheckBoxList from db table problem


enginev
April 1st, 2008, 07:00 AM
Hi to all,

I have a an checkboxlist control in a webform wich populated from a db table values , DataTextField="interest_name" DataValueField="id"





1 <asp:CheckBoxList ID="interests_CheckBoxList" runat="server" Width="100%" DataSourceID="SqlDataSource1_int" DataTextField="interest_name" DataValueField="id" >
2 </asp:CheckBoxList><asp:SqlDataSource ID="SqlDataSource1_int" runat="server" ConnectionString="<%$ ConnectionStrings:conn %>"
3 SelectCommand="SELECT [id], [interest_name] FROM [interests] WHERE ([active] = @active)">
4 <SelectParameters>
5 <asp:Parameter DefaultValue="1" Name="active" Type="Byte" />
6 </SelectParameters>
7 </asp:SqlDataSource>





then I have a storedprocedure which takes the selected values and store it to a db table.

Now I want to take these values and repopulate the checkboxlist , I tried to ryn the following function in the page load but something is wrong .. could you please help me how I could do it??





1 public void pop_checkboxes()
2 {
3
4
5
6 string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
7 SqlConnection sqlConnection1 = new SqlConnection(connectionString);
8
9 string CommandText1 = "select int_id from user_interests where user_id=1 ";
10
11
12 SqlCommand sqlComm1 = new SqlCommand(CommandText1, sqlConnection1);
13 SqlDataReader reader;
14
15
16 try
17 {
18
19 //open connection
20 sqlConnection1.Open();
21 //execute command
22 reader = sqlComm1.ExecuteReader();
23
24 CheckBoxList chkbx = (CheckBoxList)form1.FindControl("interests_CheckBoxList");
25 //get results
26 while (reader.Read())
27 {
28
29 ListItem currentCheckBox = chkbx.Items.FindByValue(reader[0].ToString());
30 if (currentCheckBox != null)
31 {
32 currentCheckBox.Selected = true;
33 }
34 }
35
36 //close reader
37 reader.Close();
38 }
39 catch
40 {
41
42 Response.Write("error");
43
44 }
45 finally
46 {
47 //close connection
48 sqlConnection1.Close();
49 }
50
51 }