how to populate listview from datatable

hlsc1983

Member
Joined
Mar 6, 2014
Messages
8
Programming Experience
1-3
i have a datatable called "dt" with only one column containing names of subjects. i want to populate a list view with the datatable. I have filled listview with datareaders in the past but this time i want to use the datatable. please help.
 
It's basically the same thing. You would use a For or For Each loop over the Rows collection of the DataTable instead of a Do or While loop over the data reader.
i tried this but the list view is blank:


VB.NET:
subjectsLvw.GridLines = True
        subjectsLvw.View = View.Details
        subjectsLvw.FullRowSelect = True
        subjectsLvw.Columns.Add("Subject name", 100)

     For Each row As DataRow In dt.Rows
       Dim lit As New ListViewItem
       lit.Text = Convert.ToString(dt.Rows())
       subjectsLvw.Items.Add(lit)
    Next
 
i got it finally.


VB.NET:
 For i As Integer = 0 To dt.Rows.Count - 1
            Dim lit As New ListViewItem
            lit.Text = Convert.ToString(dt.Rows(i).Item("subject_name"))
            subjectsLvw.Items.Add(lit)
        Next

one question here. so 'item' refers to column name???
 
i got it finally.


VB.NET:
 For i As Integer = 0 To dt.Rows.Count - 1
            Dim lit As New ListViewItem
            lit.Text = Convert.ToString(dt.Rows(i).Item("subject_name"))
            subjectsLvw.Items.Add(lit)
        Next

one question here. so 'item' refers to column name???

I assume that you're asking about this:
VB.NET:
lit.Text = Convert.ToString(dt.Rows(i).[B][U]Item[/U][/B]("subject_name"))
That is the Item property of the DataRow class. The DataRow is basically a collection of the field values in the row. You can pass either a column index or name to the property to tell it which field you want. Again, it's almost exactly the same as a data reader, which also has an Item property. In both cases, Item is the default property so you can omit the property name if you like, e.g. that line above could be written as:
VB.NET:
lit.Text = Convert.ToString(dt.Rows(i)("subject_name"))
In fact, you're already omitting one Item property here, because that line could also be written like this:
VB.NET:
lit.Text = Convert.ToString(dt.Rows.Item(i).Item("subject_name"))
 
Back
Top