1、DataTable转成ListView:
先遍历DataTable的列,把DataTable列名添加到listView列头。
然后外循环添加行,内循环添加列
跟这篇文章是一样的 http://www.cnblogs.com/Sukie-s-home/p/5702469.html
2、ListView转成DataTable:
先遍历ListView的列,把ListView列头添加到DataTable列名。
然后外循环添加行,内循环添加列 items[i].subitems[j].text
public static void dataTableToListView(ListView lv, DataTable dt) { if (dt != null) { lv.Items.Clear(); lv.Columns.Clear(); for (int i = 0; i < dt.Columns.Count; i++) { lv.Columns.Add(dt.Columns[i].Caption.ToString()); } foreach (DataRow dr in dt.Rows) { ListViewItem lvi = new ListViewItem(dr[0].ToString()); for (int i = 1; i < dt.Columns.Count; i++) { lvi.SubItems.Add(dr[i].ToString()); } lv.Items.Add(lvi); } lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } } public static void listViewToDataTable(ListView lv, DataTable dt) { dt.Clear(); dt.Columns.Clear(); //生成DataTable列头 for (int i = 0; i < lv.Columns.Count; i++) { dt.Columns.Add(lv.Columns[i].Text.Trim(), typeof(string)); } //每行内容 for (int i = 0; i < lv.Items.Count; i++) { DataRow dr = dt.NewRow(); for (int j = 0; j < lv.Columns.Count; j++) { dr[j] = lv.Items[i].SubItems[j].Text.Trim(); } dt.Rows.Add(dr); } }