Question Issue with adding item to ListView

kbsudhir

Member
Joined
Jun 13, 2008
Messages
21
Programming Experience
Beginner

Hi All,

I have a list view control in which I have create three columns.
I have three text boxes, user can enter data into these text boxes & click the button. On the button click the data in the text boxes gets added to the list view a new row.
Now, my issue is first when I enter data in the text boxes & click the button then data gets added to the listview perfectly. But when I click the button again then only first column in the list view gets populated, col 2 & col 3 do not populated...!!!! even though the textboxes 2 & 3 have data ..

VB.NET:
Public Class Form1

    Private Sub btnAddItems_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddItems.Click

        Lview.Items.Add(txtItem1.Text)
        Lview.Items(0).SubItems.Add(txtItem2.Text)
        Lview.Items(0).SubItems.Add(txtItem3.Text)

    End Sub
End Class

I am using Visual Studio 2010.

Please let me know where am I going wrong.

Regards
Sudhir
 
Last edited:

I am able fix this issue now with the help of Google.

Below is the code
VB.NET:
Public Class Form1

    Private Sub btnAddItems_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddItems.Click

        Dim LvItem As ListViewItem
        LvItem = Lview.Items.Add(txtItem1.Text)
        LvItem.SubItems.Add(txtItem2.Text)
        LvItem.SubItems.Add(txtItem3.Text)

    End Sub
End Class

But I still want to understand concept-wise where was I going wrong.

Regards
Sudhir

 
The issue with your original code is here:
VB.NET:
Public Class Form1

    Private Sub btnAddItems_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddItems.Click

        Lview.Items.Add(txtItem1.Text)
        Lview.Items([B][U][COLOR="#FF0000"]0[/COLOR][/U][/B]).SubItems.Add(txtItem2.Text)
        Lview.Items([B][U][COLOR="#FF0000"]0[/COLOR][/U][/B]).SubItems.Add(txtItem3.Text)

    End Sub
End Class
You were always using index zero so you were always adding the subitems to the first item in the ListView. It worked the first time because the item you added was the first. When you added subsequent items though, you were still adding the subitems to the first item. You can't see them because you don't have the columns in the ListView to display them, but they exist.
 
You were always using index zero so you were always adding the subitems to the first item in the ListView. It worked the first time because the item you added was the first. When you added subsequent items though, you were still adding the subitems to the first item. You can't see them because you don't have the columns in the ListView to display them, but they exist.

Thanks a lot jmcilhinney for the guidance. I really made a silly mistake in the earlier code.

Appreciating your time.

Regards
Sudhir
 
Back
Top