Reputation: 2735
I have a form which contains a checkbox field. On page load I want to create a separate checkbox for each customer in my Database. The code I have to create the checkboxes for each customer works fine. However, I also want to check in the database if the customer is set to unauthorized if they are then I want to check there box. I also have code for the case where the user checks a box. If a box is checked I update the database setting the unauthorized attribute to true. My problem is when I check a box it works fine and the box is checked, however if I reload the page all the boxes are unchecked. So either my database update is not updating the database or the way I check on page load for checked boxes is incorrect. Any ideas?
The code for the asp checkbox field:
<asp:CheckBoxList id="check1" AutoPostBack="True" TextAlign="Right" OnSelectedIndexChanged="Check" runat="server">
</asp:CheckBoxList>
The Code for the page load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sql As String = "SELECT Name, unauthorized, ID FROM Customer ORDER BY Name"
Dim dt As DataTable = db.execDataTableQuery(sql, "Customer")
Dim i As Integer
For i = 0 To dt.Rows.Count - 1
check1.Items.Add(New ListItem(CStr(dt.Rows(i).Item("Name"))))
check1.Items(i).Value = CInt(dt.Rows(i).Item("ID"))
check1.Items(i).Text = CStr(dt.Rows(i).Item("Name"))
If CInt(dt.Rows(i).Item("unauthorized")) = 1 Then
check1.Items(i).Selected = 1
Else
check1.Items(i).Selected = 0
End If
Next
End Sub
The code to update the database:
Sub Check(ByVal sender As Object, ByVal e As EventArgs)
Dim sql As String
If check1.SelectedItem.Selected = 1 Then
sql = "UPDATE Customer SET unauthorized = 1 WHERE ID = @ID"
db.execUpdateQuery(sql, New SqlClient.SqlParameter("@ID", check1.SelectedItem.Value))
Else
sql = "UPDATE Customer SET unauthorized = 0 WHERE ID = @ID"
db.execUpdateQuery(sql, New SqlClient.SqlParameter("@ID", check1.SelectedItem.Value))
End If
End Sub
End Class
Upvotes: 0
Views: 1828
Reputation: 460018
You need to wrap you code in Page_Load in a Not Page.IsPostback
, otherwise on postback no events are triggered and the selection is lost since you're overwriting it from database.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostback Then
' databind your CheckBoxList '
End If
End Sub
Upvotes: 1