涉及到数据库的编程,经常需要在listview与datatable之间传递数据,写了个简单的类,备用。
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Data;
5 using System.Data.SqlClient;
6 using System.Data.OleDb;
7 using System.Windows.Forms;
8 using System.Drawing;
9
10
11 namespace ListViewFill
12 {
13 class ListViewFill
14 {
15 //fill the listview
16 static public void dataTableToListview(ListView lv, DataTable dt)
17 {
18 if (dt != null)
19 {
20 lv.Items.Clear();
21 lv.Columns.Clear();
22 for (int i = 0; i < dt.Columns.Count; i++)
23 {
24 lv.Columns.Add(dt.Columns[i].Caption.ToString());
25 }
26 foreach (DataRow dr in dt.Rows)
27 {
28 ListViewItem lvi = new ListViewItem();
29 lvi.SubItems[0].Text = dr[0].ToString();
30
31 for (int i = 1; i < dt.Columns.Count; i++)
32 {
33 lvi.SubItems.Add(dr[i].ToString());
34 }
35
36 lv.Items.Add(lvi);
37 }
38 lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
39 }
40 }
41 static public void listViewToDataTable(ListView lv,DataTable dt)
42 {
43 int i, j;
44 DataRow dr;
45 dt.Clear();
46 dt.Columns.Clear();
47 //生成DataTable列头
48 for (i = 0; i < lv.Columns.Count; i++)
49 {
50 dt.Columns.Add(lv.Columns[i].Text.Trim(), typeof(String));
51 }
52 //每行内容
53 for (i = 0; i < lv.Items.Count; i++)
54 {
55 dr = dt.NewRow();
56 for (j = 0; j < lv.Columns.Count; j++)
57 {
58 dr[j] = lv.Items[i].SubItems[j].Text.Trim();
59 }
60 dt.Rows.Add(dr);
61 }
62 }
63 }
64 }
65
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Data;
5 using System.Data.SqlClient;
6 using System.Data.OleDb;
7 using System.Windows.Forms;
8 using System.Drawing;
9
10
11 namespace ListViewFill
12 {
13 class ListViewFill
14 {
15 //fill the listview
16 static public void dataTableToListview(ListView lv, DataTable dt)
17 {
18 if (dt != null)
19 {
20 lv.Items.Clear();
21 lv.Columns.Clear();
22 for (int i = 0; i < dt.Columns.Count; i++)
23 {
24 lv.Columns.Add(dt.Columns[i].Caption.ToString());
25 }
26 foreach (DataRow dr in dt.Rows)
27 {
28 ListViewItem lvi = new ListViewItem();
29 lvi.SubItems[0].Text = dr[0].ToString();
30
31 for (int i = 1; i < dt.Columns.Count; i++)
32 {
33 lvi.SubItems.Add(dr[i].ToString());
34 }
35
36 lv.Items.Add(lvi);
37 }
38 lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
39 }
40 }
41 static public void listViewToDataTable(ListView lv,DataTable dt)
42 {
43 int i, j;
44 DataRow dr;
45 dt.Clear();
46 dt.Columns.Clear();
47 //生成DataTable列头
48 for (i = 0; i < lv.Columns.Count; i++)
49 {
50 dt.Columns.Add(lv.Columns[i].Text.Trim(), typeof(String));
51 }
52 //每行内容
53 for (i = 0; i < lv.Items.Count; i++)
54 {
55 dr = dt.NewRow();
56 for (j = 0; j < lv.Columns.Count; j++)
57 {
58 dr[j] = lv.Items[i].SubItems[j].Text.Trim();
59 }
60 dt.Rows.Add(dr);
61 }
62 }
63 }
64 }
65