有没有一种简单的方法来通过DataTable填充ListView?

时间:2011-01-04 10:05:46

标签: .net winforms listview datatable

DataGridView有一个属性“DataSource”,可以简单地将其分配给DataTable来填充它。这意味着我们不必担心DataTable

中列的名称/数量

但是,我还没有找到类似的填充ListView的方法。您似乎需要知道DataTable有多少列以及每个列的名称,这样做会更加困难。

有人可以建议使用ListView轻松填充DataGridView吗?

2 个答案:

答案 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子类,它正是这样做的。

您可以为其提供数据源(可以是DataViewDataTableDataSetDataViewManager,或 BindingSource),它将自动创建列并填充行,以生成功能完整的列表视图。您只需要一行代码:

this.dataListView1.DataSource = ds1.Tables["Persons"];