ewein
ewein

Reputation: 2735

VB.Net Check if a checkbox list item is checked/unchecked

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

Upvotes: 1

Views: 35316

Answers (2)

user3972104
user3972104

Reputation:

You can try this also

   For i As Integer = 0 To CheckedListBox1.Items.Count - 1
        If CheckedListBox1.GetItemChecked(i) = 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
    Next

Upvotes: 1

Romil Kumar Jain
Romil Kumar Jain

Reputation: 20745

for (int i = 0; i < check1.Items.Count; i++)
  if (check1.GetItemChecked(i))
    // Do selected stuff
  else
    // Do unselected stuff

If the the check is in indeterminate state, this will still return true. You may want to replace

if (check1.GetItemChecked(i))

with

if (check1.GetItemCheckState(i) == CheckState.Checked)

if you want to only include actually checked items.

Upvotes: 1

Related Questions