0

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

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
4

2 回答 2

1

如果要检查子项是否为空或为空,可以添加如下代码行:

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

希望这会有所帮助

于 2013-05-23T12:40:48.353 回答
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
于 2013-05-23T12:37:53.950 回答