DataGridView
有一个属性“DataSource”,可以简单地将其分配给DataTable
来填充它。这意味着我们不必担心DataTable
。
但是,我还没有找到类似的填充ListView
的方法。您似乎需要知道DataTable
有多少列以及每个列的名称,这样做会更加困难。
有人可以建议使用ListView
轻松填充DataGridView
吗?
答案 0 :(得分:3)
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);
}
}
}
查找排序等也 - http://www.akadia.com/services/dotnet_listview_sort_dataset.html
修改 -
// 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);
}
}
答案 1 :(得分:2)
ObjectListView - 一个围绕.NET WinForms ListView的开源包装器 - 有一个DataListView
子类,它正是这样做的。
您可以为其提供数据源(可以是DataView
,
DataTable
,
DataSet
,
DataViewManager
,或
BindingSource
),它将自动创建列并填充行,以生成功能完整的列表视图。您只需要一行代码:
this.dataListView1.DataSource = ds1.Tables["Persons"];