如何检查ListView SubItem中的null或空项?

时间:2013-05-23 12:27:32

标签: vb.net listview

我创建了这个列表视图框,当双击内容时,值将被插入文本框中。某些项目中有空格,并且子项中有一对具有空值。单击这些特定列表项时,它会崩溃软件。有没有办法可以检查子项是空还是空?

Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
    For i As Integer = 1 To 7
        Dim tbName As String = "TextBox" & i
        Dim matches() As Control = Me.Controls.Find(tbName, True)
        If matches.Length > 0 AndAlso TypeOf matches(0) Is TextBox Then
            Dim tb As TextBox = DirectCast(matches(0), TextBox)
            If tb.Text.Trim.Length = 0 Then
                tb.Text = ListView1.SelectedItems(0).SubItems(0).Text
                Exit Sub
            End If
        End If
    Next

2 个答案:

答案 0 :(得分:0)

尝试向ListView1.SelectedItems(0).SubItems(0).Text

添加一些验证

有时似乎是空的:

使用此验证:

If Not ListView1.SelectedItems is Nothing
   AndAlso Not ListView1.SelectedItems(0) is Nothing
   AndAlso Not string.IsNullOrEmpty(ListView1.SelectedItems(0).SubItems(0).Text)  Then

                tb.Text = ListView1.SelectedItems(0).SubItems(0).Text
End if

完整代码:

Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
    For i As Integer = 1 To 7
        Dim tbName As String = "TextBox" & i
        Dim matches() As Control = Me.Controls.Find(tbName, True)
        If matches.Length > 0 AndAlso TypeOf matches(0) Is TextBox Then
            Dim tb As TextBox = DirectCast(matches(0), TextBox)
            If tb.Text.Trim.Length = 0 Then
              If Not ListView1.SelectedItems is Nothing
                     AndAlso Not ListView1.SelectedItems(0) is Nothing
                     AndAlso Not string.IsNullOrEmpty(ListView1.SelectedItems(0).SubItems(0).Text)  Then
                tb.Text = ListView1.SelectedItems(0).SubItems(0).Text
              End if
                Exit Sub
            End If
        End If
    Next

答案 1 :(得分:0)

如果你想检查一个子项是空还是空,你可以添加类似这行代码的东西:

If tb.Text.Trim.Length = 0 Then
      'check if subitem isn't null and its text is not ""
       If Not IsNothing(ListView1.SelectedItems(0).SubItems(0)) AndAlso ListView1.SelectedItems(0).SubItems(0).Text <> "" Then
            tb.Text = ListView1.SelectedItems(0).SubItems(0).Text
            Exit Sub
       End if
End If

希望这是有帮助的