I have a checkbox list which is filled with entries from my database on page load. I need to update an entry in my database when a item is checked and when an item is unchecked. Right now I am doing the following:
<asp:CheckBoxList id="check1" AutoPostBack="True" TextAlign="Right" OnSelectedIndexChanged="Check" runat="server">
</asp:CheckBoxList>
And the function:
Sub Check(ByVal sender As Object, ByVal e As EventArgs)
Dim sql As String
If check1.SelectedItem.Selected = True Then
sql = "UPDATE Customer SET unauthorized = 'True' WHERE ID = @ID"
db.execUpdateQuery(sql, New SqlClient.SqlParameter("@ID", check1.SelectedItem.Value))
Else
sql = "UPDATE Customer SET unauthorized = 'False' WHERE ID = @ID"
db.execUpdateQuery(sql, New SqlClient.SqlParameter("@ID", check1.SelectedItem.Value))
End If
End Sub
But when I uncheck a button the else case is never ran. Also, if I have 4 buttons checked and I uncheck all four buttons, when I uncheck the fourth button I get an error at the line:
If check1.SelectedItem.Selected = True Then
The error is: “Object reference not set to an instance of an object.”
Is there a better way to check if a list item is checked or unchecked?
Thanks
If the the check is in indeterminate state, this will still return true. You may want to replace
with
if you want to only include actually checked items.