Listview Error

tehon3299

Centurion
Joined
Jan 6, 2003
Messages
155
Location
Liverpool, NY
Why am I getting an error that says I can only add "First Item" in one spot or I must remove or clone it?
Visual Basic:
        Dim listViewItem As New ListViewItem()
        Dim ctr As Integer = 0

        lvw.View = View.Details
        lvw.Columns.Add("First Column", 100, HorizontalAlignment.Center)
        lvw.Columns.Add("Second Column", 100, HorizontalAlignment.Center)
        lvw.Columns.Add("Third Column", 100, HorizontalAlignment.Center)

        For ctr = 0 To 5
            listViewItem.Text = "First Item"
            listViewItem.SubItems.Add("Second Item")
            listViewItem.SubItems.Add("Third Item")
            lvw.Items.Add(listViewItem)
        Next

    End Sub

Am I adding the ListViewItem to the lvw wrong? If I move the lvw.Items.Add(listViewItem) outside the loop it works fine but obviously only does it once. Once I move it into the loop, it bombs.
 
Avoid naming a variable the same as the type (listViewItem)

Try this....
Visual Basic:
         lvw.Columns.Add("First Column", 100, HorizontalAlignment.Center)
        lvw.Columns.Add("Second Column", 100, HorizontalAlignment.Center)
        lvw.Columns.Add("Third Column", 100, HorizontalAlignment.Center)
        lvw.Columns.Add("Forth Column", 100, HorizontalAlignment.Center)
        lvw.Columns.Add("Fifth Column", 100, HorizontalAlignment.Center)

        Dim ctr As Integer
        For ctr = 1 To 10
            Dim item1 As New ListViewItem(ctr.ToString)
            item1.SubItems.Add("Two " & ctr.ToString)
            item1.SubItems.Add("Three " & ctr.ToString)
            item1.SubItems.Add("Four " & ctr.ToString)
            item1.SubItems.Add("Five " & ctr.ToString)
            lvw.Items.AddRange(New ListViewItem() {item1})
        Next
 
Back
Top