Rafiq
Rafiq

Reputation: 103

Populate simple listview

listView1 is set to details and have 2 columns. So I want to populate listView1 with number1 and number2. Each number should figure in its respective column. But I don't know how to do that, so please help.

Thank you.

Public Class Form1

Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click
    Dim myItem As New ListViewItem
    Dim number1 As Decimal
    Dim number2 As Decimal
    Dim rand As New Random

    listView1.Items.Clear()

    For a As Integer = 1 To 20
        number1 = rand.Next(1, 20 + 1)
        number2 = rand.Next(1, 20 + 1)
        If number1 Mod number2 = 0 Then
            'put number1 and number2 in listview1
        End If
    Next

End Sub

End Class

Upvotes: 0

Views: 48

Answers (1)

David Wilson
David Wilson

Reputation: 4439

The code below assume you already have added two columns to your listview

If so, this should do it.

Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click
    Dim myItem As New ListViewItem
    Dim number1 As Decimal
    Dim number2 As Decimal
    Dim rand As New Random

    ListView1.Items.Clear()

    For a As Integer = 1 To 20
        number1 = rand.Next(1, 20 + 1)
        number2 = rand.Next(1, 20 + 1)
        If number1 Mod number2 = 0 Then
            Dim newRow As New ListViewItem(number1.ToString)
            newRow.SubItems.Add(number2.ToString)
            ListView1.Items.Add(newRow)
        End If
    Next

End Sub

If you dont already have two columns then you either need to add them in control's properties in the Visual Studio designer, or somewhere appropriate in your code - not in the button click event of course, because this will keep adding columns every time you click the button.

If you're not sure how to do this programattically - try this : -

ListView1.Columns.Add("number1")
ListView1.Columns.Add("number2")

The names of the columns can be anything in quotes. The fact that I chose "numbers1" and "numbers2" isn't important

I can't tell you where to put this in your code, but a good bet would be in the form.load event

Upvotes: 2

Related Questions