如何删除listview中的项目? vb.net

时间:2014-01-06 02:54:39

标签: vb.net

我填充listview中的项目,当我单击命令按钮时,我将在数据库的列表中添加项目,如果列表中的项目尚未签出,它将从中删除项目下面填充的列表是我的代码。

Dim y As Integer
Dim a As String
y = ListView2.Items.Count
While y >= 0
    a = ListView2.Items.Item(y).Text
    y = y - 1

    Dim TMP_SQL_VAL As String = "select count([Check-Out]) from tbl_list1 where barcode = '" + a + "'"
    locconn.Open()
    command = New SqlCommand(TMP_SQL_VAL, locconn)
    Dim READER As SqlDataReader
    READER = command.ExecuteReader()
    READER.Read()

    If READER(0) = 0 Then
        MsgBox("Barcode: " & a & "is still Inside", MsgBoxStyle.Exclamation)
        clear_text()

        ListView2.Items.Remove(y)
    Else
        READER.Close()
        Dim READER2 As SqlDataReader
        Dim TMP_SQL_VAL2 = "select [Check-In] from tbl_list1 where barcode = '" + a + "' and  [User] = '" + rsuser + "'"
        Dim cmd = New SqlCommand(TMP_SQL_VAL2, locconn)
        READER2 = cmd.ExecuteReader
        READER2.Read()
        If READER2(0) Is Nothing Then
            MsgBox("Barcode: " & a & "is still Inside", MsgBoxStyle.Exclamation)
            clear_text()
        ListView2.Items.Remove(y)
        End If
   end if
   locconn.Close()
End While

Catch ex As Exception
    MsgBox(ex.Message)
    localconn.ShowDialog()
Finally
    locconn.Close()
End Try

1 个答案:

答案 0 :(得分:0)

尝试检查y的值是否为< 0,如果没有,则无需处理终止

Dim y As Integer
Dim a As String
y = ListView2.Items.Count - 1 'Reduce 1
If y < 0 Then return 'If no item then terminate
While y >= 0
    a = ListView2.Items.Item(y).Text
    'y = y - 1    'Moved to last line before End While
    Dim TMP_SQL_VAL As String = "select count([Check-Out]) from tbl_list1 where barcode = '" + a + "'"
    locconn.Open()
    command = New SqlCommand(TMP_SQL_VAL, locconn)
    Dim READER As SqlDataReader
    READER = command.ExecuteReader()
    READER.Read()

    If READER(0) = 0 Then
        MsgBox("Barcode: " & a & "is still Inside", MsgBoxStyle.Exclamation)
        clear_text()

        ListView2.Items.Remove(y)
    Else
        READER.Close()
        Dim READER2 As SqlDataReader
        Dim TMP_SQL_VAL2 = "select [Check-In] from tbl_list1 where barcode = '" + a + "' and  [User] = '" + rsuser + "'"
        Dim cmd = New SqlCommand(TMP_SQL_VAL2, locconn)
        READER2 = cmd.ExecuteReader
        READER2.Read()
        If READER2(0) Is Nothing Then
            MsgBox("Barcode: " & a & "is still Inside", MsgBoxStyle.Exclamation)
            clear_text()
        ListView2.Items.Remove(y)
        End If
   end if
   locconn.Close()

   y -= 1  'Move here so the value is decremented before the While statement

End While

Catch ex As Exception
    MsgBox(ex.Message)
    localconn.ShowDialog()
Finally
    locconn.Close()
End Try