如何创建DataSet,并用DataGridView显示数据
13 #region DataSet测试 by Jrain 2008年7月27日 17时40分40秒
14 /// <summary>
15 /// 创建DataSet并在DataGridView中显示构建的表结构
16 /// </summary>
17 /// <returns></returns>
18 private DataSet CreateDataSet()
19 {
20 //创建DataSet对象
21 DataSet stuDS = new DataSet();
22 //创建DataTable对象
23 DataTable stuTable = new DataTable("Students");
24 //创建DataColumn对象
25 DataColumn stuColumn = new DataColumn();
26 //构建表结构,添加列
27
28 stuColumn.DataType = System.Type.GetType("System.Int32");//注意类型应该是System.Int32,而不能直接写Int32
29 stuColumn.ColumnName = "stuNo";
30 stuColumn.AllowDBNull = false;
31 //把列添加到Table中
32 stuTable.Columns.Add(stuColumn);
33
34 //往表中添加列
35 stuTable.Columns.Add("stuName",typeof(string));
36 stuTable.Columns.Add("stuAge",typeof(int));
37 //创建DataRow对象
38 DataRow stuRow = stuTable.NewRow();
39 //新增数据
40 stuRow["stuNo"] = 101;
41 stuRow["stuName"] = "sofie";
42 stuRow["stuAge"] = 21;
43 //把数据添加到表结构中
44 stuTable.Rows.Add(stuRow);
45
46 stuRow = stuTable.NewRow();
47 stuRow["stuNo"] = 102;
48 stuRow["stuName"] = "Jrain";
49 stuRow["stuAge"] = 26;
50 stuTable.Rows.Add(stuRow);
51 //将表结构添加到DataSet中
52 stuDS.Tables.Add(stuTable);
53
54 return stuDS;
55
56
57 }
58 #endregion
59
60
61 private void btnAdd_Click(object sender, EventArgs e)
62 {
63 this.dgvStudent.DataSource = this.CreateDataSet();
64 //必须是创建的DataTable的名字
65 this.dgvStudent.DataMember = "Students";
66 }
14 /// <summary>
15 /// 创建DataSet并在DataGridView中显示构建的表结构
16 /// </summary>
17 /// <returns></returns>
18 private DataSet CreateDataSet()
19 {
20 //创建DataSet对象
21 DataSet stuDS = new DataSet();
22 //创建DataTable对象
23 DataTable stuTable = new DataTable("Students");
24 //创建DataColumn对象
25 DataColumn stuColumn = new DataColumn();
26 //构建表结构,添加列
27
28 stuColumn.DataType = System.Type.GetType("System.Int32");//注意类型应该是System.Int32,而不能直接写Int32
29 stuColumn.ColumnName = "stuNo";
30 stuColumn.AllowDBNull = false;
31 //把列添加到Table中
32 stuTable.Columns.Add(stuColumn);
33
34 //往表中添加列
35 stuTable.Columns.Add("stuName",typeof(string));
36 stuTable.Columns.Add("stuAge",typeof(int));
37 //创建DataRow对象
38 DataRow stuRow = stuTable.NewRow();
39 //新增数据
40 stuRow["stuNo"] = 101;
41 stuRow["stuName"] = "sofie";
42 stuRow["stuAge"] = 21;
43 //把数据添加到表结构中
44 stuTable.Rows.Add(stuRow);
45
46 stuRow = stuTable.NewRow();
47 stuRow["stuNo"] = 102;
48 stuRow["stuName"] = "Jrain";
49 stuRow["stuAge"] = 26;
50 stuTable.Rows.Add(stuRow);
51 //将表结构添加到DataSet中
52 stuDS.Tables.Add(stuTable);
53
54 return stuDS;
55
56
57 }
58 #endregion
59
60
61 private void btnAdd_Click(object sender, EventArgs e)
62 {
63 this.dgvStudent.DataSource = this.CreateDataSet();
64 //必须是创建的DataTable的名字
65 this.dgvStudent.DataMember = "Students";
66 }