我在删除listview中的最后一项时遇到问题。如果我有,让我们说列表视图中有3个联系人,删除3个联系人中的2个是没问题的。列表视图将自动刷新,3个联系人中的2个将从列表中删除。但是,如果我要删除最后一个和第三个联系人,列表视图将不会更新或刷新,除非我退出表单并重新打开它。
以下是我的代码
Private Sub ContactTab_load()
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = Search.sqlConnect
sConnection.Open()
End If
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTable As New DataTable
Dim sqlText As String
nameForm.nameSearch = nameForm.nameListView.SelectedItems(0).Text
Dim InstitutionContactName As String = nameForm.nameSearch
InstitutionContactName = InstitutionContactName.Replace("'", "''")
sqlText = "select c.contact_id, c.contact_first_name,c.contact_last_name,c.primary_phone,c.primary_email, ct.contact_type_name, ihc.institution_id from institution i left outer join institution_has_contact ihc on i.institution_id = ihc.institution_id left outer join contact c on ihc.contact_id = c.contact_id join contact_type ct on ct.contact_type_id = c.contact_type_id where institution_name='" & InstitutionContactName & "' order by contact_first_name"
If Search.debugging Then
MsgBox("sql=" & sqlText)
End If
With sqlCommand
.CommandText = sqlText
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTable)
End With
If sqlTable.Rows.Count > 0 Then
InstitutionContactListView.Items.Clear()
For i = 0 To sqlTable.Rows.Count - 1
With InstitutionContactListView
.Items.Add(sqlTable.Rows(i)("contact_id"))
With .Items(.Items.Count - 1).SubItems
.Add(sqlTable.Rows(i)("contact_first_name"))
.Add(sqlTable.Rows(i)("contact_last_name"))
.Add(sqlTable.Rows(i)("primary_phone"))
.Add(sqlTable.Rows(i)("primary_email"))
.Add(sqlTable.Rows(i)("contact_type_name"))
End With
End With
Next
sqlTable.Dispose()
sqlCommand.Dispose()
sqlAdapter.Dispose()
End If
If InstitutionContactListView.Items.Count > 0 Then
InstitutionContactListView.Items(0).Selected = True
End If
End Sub
这是删除联系人的代码
Private Sub RemoveContactButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RemoveContactButton.Click
If ContactIDSelected > -1 Then
RunSql("delete from institution_has_contact where institution_id = " & InstitutionID & " and contact_ID=" & ContactIDSelected)
ContactTab_load()
Else
MsgBox("Select a Contact to be removed")
End If
End Sub
为什么会发生这种情况的任何想法?
答案 0 :(得分:1)
您的ContactTab_load
程序未考虑查询返回的行:
If sqlTable.Rows.Count > 0 Then
InstitutionContactListView.Items.Clear()
For i = 0 To sqlTable.Rows.Count - 1
With InstitutionContactListView
' ...
将Clear移动到循环外部,以便在删除/删除最后一项时,LV被清除:
InstitutionContactListView.Items.Clear()
If sqlTable.Rows.Count > 0 Then
For i = 0 To sqlTable.Rows.Count - 1
With InstitutionContactListView
' ...
或者,添加一个ELSE来做同样的事情。