Set check status for asp:checkboxlist items as loaded from a database




Set check status for asp:checkboxlist items as loaded from a database
If you have recorded which items were selected in a asp:checkbox list to a database and now you want to reload that selection ticking each box as stored in your database, this is how you do it:
 
This is your checkboxlist:
  1. <asp:checkboxlist id="chk1" runat="server" datavaluefield="CatID" datatextfield="CatName" />  

The below exaple shows how to check each item that is recorded in your database:
  1. Dim MyConnection As SqlConnection   
  2.     MyConnection = New SqlConnection()   
  3.     MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString   
  4.   
  5. Dim sql As String = "SELECT UserID, CatID FROM SELECTIONS"  
  6.         Dim objDR As SqlDataReader   
  7.         Dim CmdR As New SqlCommand(sql, MyConnection)   
  8.         MyConnection.Open()   
  9.         objDR = CmdR.ExecuteReader(System.Data.CommandBehavior.CloseConnection)   
  10.         Do While objDR.Read()   
  11.             Dim i As Int32   
  12.             For i = 0 To chk1.Items.Count - 1   
  13.                 Dim strChkID As String = objDR("CatID")   
  14.                 If chk1.Items(i).Value = strChkID Then  
  15.                     chk1.Items.Item(i).Selected = True  
  16.                 End If  
  17.             Next  
  18.         Loop  
  19.         MyConnection.Close()  


No one has said that they like article yet, be the first and click here (0)
Send a link to this page via email Send a link to this page