Reputation: 3435
I have seen many examples of populating a listview from a datatable or converting a datatable to a listview but what I am trying to do is exactly the other way around.
How can I convert/copy the contents of a winform listview to a datatable?
[EDIT]
I have a listview with a context menu where users can multiselect items and choose one of the context menu options, I then loop the selected items and extract each selected row (listview item) and serialize it, instead of doing this I wanted to convert the listview to a datatable then add the datatable to a dataset and serialize the dataset.
Thanks
Upvotes: 0
Views: 18939
Reputation: 1507
Accepted answer doesn't look right to me. Here is a tested alternative:
public static void FromListView(DataTable table, ListView lvw)
{
table.Clear();
var columns = lvw.Columns.Count;
foreach (ColumnHeader column in lvw.Columns)
table.Columns.Add(column.Text);
foreach (ListViewItem item in lvw.Items)
{
var cells = new object[columns];
for (var i = 0; i < columns; i++)
cells[i] = item.SubItems[i].Text;
table.Rows.Add(cells);
}
}
Upvotes: 3
Reputation: 1
DataTable table = new DataTable();
table.Columns.Add("MODUL", typeof(string));
table.Columns.Add("ACIKLAMA", typeof(string));
table.Columns.Add("UZUNLUK", typeof(string));
table.Columns.Add("GENISLIK", typeof(string));
table.Columns.Add("MIKTAR", typeof(string));
for (int i = 0; i < listView2.Items.Count; i++)
{
table.Rows.Add(listView2.Items[i].SubItems[0].Text, listView2.Items[i].SubItems[1].Text, listView2.Items[i].SubItems[2].Text, listView2.Items[i].SubItems[3].Text, listView2.Items[i].SubItems[4].Text);
} //Which Subitems you want to add in the listview
Upvotes: 0
Reputation: 60493
something like that (totally untested)
var listView1 = new ListView();
DataTable table = new DataTable();
foreach (ListViewItem item in listView1.Items)
{
table.Columns.Add(item.ToString());
foreach (var it in item.SubItems)
table.Rows.Add(it.ToString());
}
Upvotes: 4