选择性将datatable的列绑定到gridview
--
Code
1 //绑定所有列
2 string connStr = @"Data Source=192.168.1.2\sqlexpress;Initial Catalog=SchoolMIS1ForBS;User ID=sa;password=sa1";
3 SqlConnection conn = new SqlConnection(connStr);
4 SqlCommand cmd = conn.CreateCommand();
5 cmd.CommandText = "select top 10 * from sysobjects";
6 SqlDataAdapter sda = new SqlDataAdapter(cmd);
7 DataTable dt = new DataTable();
8 sda.Fill(dt);
9 GridView1.DataSource = dt;
10 GridView1.DataBind();
11
12
13 //绑定指定列1
14 string columns =",name,id,xtype,";
15 for (int i = 0; i < dt.Columns.Count; i++)
16 {
17 if (columns.Contains(","+ dt.Columns[i].ColumnName + ","))
18 continue;
19 dt.Columns.Remove(dt.Columns[i].ColumnName);
20 i = 0;//这一句至关重要,由于remove之后dt.columns.count发生变化(循环控制变量被改变),导致循环次数减少,所以这里需要重置循环变量,使循环重新开始
21 }
22 GridView1.DataBind();
23 return;
24
25
26 //绑定指定列2
27 columns = ",name,id,xtype,";
28 string[] arr = new string[dt.Columns.Count];
29 //首先将循环依赖的因素(循环条件)读入一个数组,以后的操作以此数据为判断依据
30 for (int i = 0; i < dt.Columns.Count; i++)
31 {
32 arr[i] = dt.Columns[i].ColumnName;
33 }
34 //使用刚才的数据进行循环控制
35 for (int i = 0; i < arr.Length; i++)
36 {
37 if (columns.Contains("," + arr[i] + ","))//改变dt.columns时循环条件不受影响
38 continue;//这里可以使用else结构代替continue,但是效率稍低
39 dt.Columns.Remove(arr[i]);
40 }
41 GridView1.DataBind();
1 //绑定所有列
2 string connStr = @"Data Source=192.168.1.2\sqlexpress;Initial Catalog=SchoolMIS1ForBS;User ID=sa;password=sa1";
3 SqlConnection conn = new SqlConnection(connStr);
4 SqlCommand cmd = conn.CreateCommand();
5 cmd.CommandText = "select top 10 * from sysobjects";
6 SqlDataAdapter sda = new SqlDataAdapter(cmd);
7 DataTable dt = new DataTable();
8 sda.Fill(dt);
9 GridView1.DataSource = dt;
10 GridView1.DataBind();
11
12
13 //绑定指定列1
14 string columns =",name,id,xtype,";
15 for (int i = 0; i < dt.Columns.Count; i++)
16 {
17 if (columns.Contains(","+ dt.Columns[i].ColumnName + ","))
18 continue;
19 dt.Columns.Remove(dt.Columns[i].ColumnName);
20 i = 0;//这一句至关重要,由于remove之后dt.columns.count发生变化(循环控制变量被改变),导致循环次数减少,所以这里需要重置循环变量,使循环重新开始
21 }
22 GridView1.DataBind();
23 return;
24
25
26 //绑定指定列2
27 columns = ",name,id,xtype,";
28 string[] arr = new string[dt.Columns.Count];
29 //首先将循环依赖的因素(循环条件)读入一个数组,以后的操作以此数据为判断依据
30 for (int i = 0; i < dt.Columns.Count; i++)
31 {
32 arr[i] = dt.Columns[i].ColumnName;
33 }
34 //使用刚才的数据进行循环控制
35 for (int i = 0; i < arr.Length; i++)
36 {
37 if (columns.Contains("," + arr[i] + ","))//改变dt.columns时循环条件不受影响
38 continue;//这里可以使用else结构代替continue,但是效率稍低
39 dt.Columns.Remove(arr[i]);
40 }
41 GridView1.DataBind();