转载自:http://blog.sina.com.cn/s/blog_4b3485000100prhl.html
代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Data; 5 using System.Windows.Forms; 6 7 namespace DesignPatternTest 8 { 9 class ListViewFill 10 { 11 /// <summary> 12 /// 为ListView绑定DataTable数据项 13 /// </summary> 14 /// <param name="dt">DataTable</param> 15 /// <param name="lv">ListView控件</param> 16 static public void dataTableToListview(DataTable dt, ListView lv) 17 { 18 if (dt != null) 19 { 20 lv.View = View.Details; 21 lv.GridLines = true;//显示网格线 22 lv.Items.Clear();//所有的项 23 lv.Columns.Clear();//标题 24 for (int i = 0; i < dt.Columns.Count; i++) 25 { 26 lv.Columns.Add(dt.Columns[i].Caption.ToString());//增加标题 27 } 28 for (int i = 0; i < dt.Rows.Count; i++) 29 { 30 ListViewItem lvi = new ListViewItem(dt.Rows[i][0].ToString()); 31 for (int j = 0; j < dt.Columns.Count; j++) 32 { 33 // lvi.ImageIndex = 0; 34 lvi.SubItems.Add(dt.Rows[i][j].ToString()); 35 } 36 lv.Items.Add(lvi); 37 } 38 lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);//调整列的宽度 39 } 40 } 41 42 /// <summary> 43 /// ListView反向填充DataTable数据项 44 /// </summary> 45 /// <param name="lv">ListView控件</param> 46 /// <param name="dt">DataTable</param> 47 static public void listViewToDataTable(ListView lv, DataTable dt) 48 { 49 DataRow dr; 50 dt.Clear(); 51 dt.Columns.Clear(); 52 for (int k = 0; k < lv.Columns.Count; k++) 53 { 54 dt.Columns.Add(lv.Columns[k].Text.Trim().ToString());//生成DataTable列头 55 } 56 for (int i = 0; i < lv.Items.Count; i++) 57 { 58 dr = dt.NewRow(); 59 for (int j = 0; j < lv.Columns.Count; j++) 60 { 61 dr[j] = lv.Items[i].SubItems[j].Text.Trim(); 62 } 63 dt.Rows.Add(dr);//每行内容 64 } 65 } 66 } 67 }