Reputation: 26517
The DataGridView
has a property "DataSource" that can simply be assigned to a DataTable
to populate it. This means we don't have to worry about the names/number of columns in the DataTable
.
But, I haven't found a similar way of populating a ListView
. It seems that you need to know how many columns the DataTable
has and the names of each in order to do this, making it much more difficult.
Can anyone suggest an easy way to populate a ListView
like we can with a DataGridView
?
Upvotes: 2
Views: 15414
Reputation: 116
private void LoadList()
{
// Get the table from the data set
DataTable dtable = _DataSet.Tables["Titles"];
// Clear the ListView control
listView1.Items.Clear();
// Display items in the ListView control
for (int i = 0; i < dtable.Rows.Count; i++)
{
DataRow drow = dtable.Rows[i];
// Only row that have not been deleted
if (drow.RowState != DataRowState.Deleted)
{
// Define the list items
ListViewItem lvi = new ListViewItem(drow["title"].ToString());
lvi.SubItems.Add (drow["title_id"].ToString());
lvi.SubItems.Add (drow["price"].ToString());
lvi.SubItems.Add (drow["pubdate"].ToString());
// Add the list items to the ListView
listView1.Items.Add(lvi);
}
}
}
Find sorting etc also at - http://www.akadia.com/services/dotnet_listview_sort_dataset.html
Modified -
// Clear the ListView control
listView1.Items.Clear();
int ColCount = dtable.Columns.Count;
//Add columns
for (int k = 0; k < ColCount; k++)
{
listView1.Columns.Add(dtable.Columns[k].ColumnName);
}
// Display items in the ListView control
for (int i = 0; i < dtable.Rows.Count; i++)
{
DataRow drow = dtable.Rows[i];
// Only row that have not been deleted
if (drow.RowState != DataRowState.Deleted)
{
// Define the list items
ListViewItem lvi = new ListViewItem(drow[0].ToString());
for (int j = 1; j < ColCount; j++)
{
lvi.SubItems.Add(drow[j].ToString());
}
// Add the list items to the ListView
listView1.Items.Add(lvi);
}
}
Upvotes: 5
Reputation: 6882
ObjectListView -- an open source wrapper around a .NET WinForms ListView -- has a DataListView
subclass which does exactly this.
You can give it a data source (which can be a DataView
,
DataTable
,
DataSet
,
DataViewManager
, or
BindingSource
), and it will auto create columns and fill in the rows, to make fully functional list view. You just need one line of code:
this.dataListView1.DataSource = ds1.Tables["Persons"];
Upvotes: 3