[RESOLVED] Adding to listview from access database(vs 2008)
My problem is very simple, i have 4 columns at the moment, this code is supposed to add the column name, and then the details to a listview. Sounds easy, but what i am getting is that all the row details are being listed in column 1. Can anyone tell me why the rows are not been added to the right column?
Code:
For i = 0 To ds.Tables("Contacts").Columns.Count - 1 'Loops until all columns have been added
'Stores column name as string
strColumnName = ds.Tables("Contacts").Columns.Item(i).ColumnName
'Skip over column ID
If strColumnName = "ID" Then
Else
'Add Column name to listview
lv1.Columns.Add(strColumnName)
'Loop until rows have been added
For j = 0 To ds.Tables("Contacts").Rows.Count - 1
'Add Row name to string
strRowName = ds.Tables("Contacts").Rows(j).Item(strColumnName).ToString
'Add string to listview
lv1.Items.Add(strRowName)
Next
lv1.Update()
End If
Thanks in advance
Redmo
Re: Adding to listview from access database(vs 2008)
You keep adding items to the ListView. At no point do you add any subitems to an item, which is how you populate columns other than the first. Your code should look something like this:
vb.net Code:
Private Sub PopulateListView(ByVal list As ListView, ByVal table As DataTable)
list.BeginUpdate()
For Each column As DataColumn In table.Columns
list.Columns.Add(column.ColumnName)
Next
Dim upperBound As Integer = table.Columns.Count - 1
Dim item As ListViewItem
For Each row As DataRow In table.Rows
item = New ListViewItem(row(0).ToString())
For index As Integer = 1 To upperBound
item.SubItems.Add(row(index).ToString())
Next
item.Tag = row
list.Items.Add(item)
Next
list.EndUpdate()
End Sub
Note that I store the corresponding DataRow in each ListViewItem's Tag property. This is unnecessary if you don't need access to the row from the item but doesn't hurt.
By the way, this question has nothing to do with databases and therefore belongs in the VB.NET forum. The fact that the data in the DataTable comes from a database is irrelevant. A DataTable is a DataTable, wherever the data came from. It's with the ListView you're having the problem and that's a purely VB issue.
Re: Adding to listview from access database(vs 2008)
Thanks jmcilhinney. Your a genius. Code worked a treat. Sorry about posting in the wrong area. At the time of the posting i was convinced that i was reading from the datatable wrong.
Redmo