iProgramIt
iProgramIt

Reputation: 1

How would I insert items from textbox into listview?

I have a listview with two columns. I also have a textbox. In the textbox, there are lines with strings that I want to insert into the listview. Every 1st line will be inserted into the first column and every 2nd line will be inserted into the second column. How would I achieve this. This is my current code:


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

Upvotes: 0

Views: 2106

Answers (1)

Hockenberry
Hockenberry

Reputation: 462

Note: You can us Math.Mod to check if you have to handle the first or second row. For example

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

I use ListView1.Clear to make sure, i'm refilling an empty ListView.

Example Code. This copies all lines from the TextBox1 to the ListView1. Separeted by a pipe |. Delete the IIf(String.IsNullOrEmpty(strView2), "", "|") & if you don't want this separation.

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

Upvotes: 1

Related Questions