Set check status for asp:checkboxlist items as loaded from a database
Thursday 10 September 2009
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:
-
<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:
- Dim MyConnection As SqlConnection
- MyConnection = New SqlConnection()
- MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
-
- Dim sql As String = "SELECT UserID, CatID FROM SELECTIONS"
- Dim objDR As SqlDataReader
- Dim CmdR As New SqlCommand(sql, MyConnection)
- MyConnection.Open()
- objDR = CmdR.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
- Do While objDR.Read()
- Dim i As Int32
- For i = 0 To chk1.Items.Count - 1
- Dim strChkID As String = objDR("CatID")
- If chk1.Items(i).Value = strChkID Then
- chk1.Items.Item(i).Selected = True
- End If
- Next
- Loop
- MyConnection.Close()
|
(0)
|
|
|