如何将文本框中的项目插入listview?

时间:2015-03-09 03:56:08

标签: vb.net

我有一个包含两列的列表视图。我也有一个文本框。在文本框中,有一些包含字符串的行我想插入到列表视图中。 每第1行将插入第一列,每第2行将插入第二列。我怎么做到这一点。 这是我目前的代码:


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    TextBox3.Text = My.Resources.clsid
    Dim ListArr(230) As String
    Dim i As Integer = 0
    For Each line As String In TextBox3.Lines
        ListArr(i) = line(i)
        i += 1
        For Each litem As String In ListArr
            AddLitem(litem, litem)
        Next
    Next
End Sub
Public Function AddLitem(ByVal Desc As String, ByVal CLSID As String)
    Dim litem As ListViewItem
    If i = 0 Then
        Lstr(0) = Desc
        i += 1
    ElseIf i = 1 Then
        Lstr(1) = Desc
        litem = New ListViewItem(Lstr)
        ListView1.Items.Add(litem)
        ListView1.Items.RemoveAt(ListView1.Items.Count)
    End If
    Lstr(0) = Desc
    'Lstr(1) = CLSID
End Function

1 个答案:

答案 0 :(得分:1)

注意: 您可以Math.Mod检查是否必须处理第一行或第二行。 例如

0 mod 2        result 0
1 mod 2        result 1
2 mod 2        result 0
3 mod 2        result 1

我使用ListView1.Clear来确保,我正在重新填充一个空的ListView。

示例代码。这会复制TextBox1ListView1的所有行。 由管道|发出。 如果您不想要这种分离,请删除IIf(String.IsNullOrEmpty(strView2), "", "|") &

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim strView1 As String = ""
        Dim strView2 As String = ""

        For i As Integer = 0 To TextBox1.Lines.Count - 1
            If (i Mod 2) Then
                strView2 &= IIf(String.IsNullOrEmpty(strView2), "", "|") & TextBox1.Lines(i)
            Else
                strView1 &= IIf(String.IsNullOrEmpty(strView1), "", "|") & TextBox1.Lines(i)
            End If
        Next

        ListView1.Clear()
        ListView1.Items.Add(strView1)
        ListView1.Items.Add(strView2)
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        TextBox1.Text = "cat" & vbCrLf & "street" & vbCrLf & "dog" & vbCrLf & "house" & vbCrLf & "bird" & vbCrLf & "garden"
    End Sub

End Class