ADO.NET编程(3)在内存中对DataTable进行增/删/改操作

  我们可以在内存中创建DataTable对象,同样也可以对它们进行进一步的各种操作,下面的示例程序中,让我们来学习如何对它们进行基本的增删改的操作。作为示例程序的第一步我们应该是先创建一个Windows Forms的项目,然后定义一个存储和传递数据的类。

 

1.定义一个Employee类

  在Employee类中定义基本的成员属性,构造函数和获取对象集合的静态方法。如下:

View Code
 1       /// <summary>
 2       /// 员工类
 3       /// </summary>
 4       public class Employee
 5       {
 6           /// <summary>
 7           /// 员工ID
 8           /// </summary>
 9           public Int64 ID { get; set; }
10   
11           /// <summary>
12           /// 全名
13           /// </summary>
14           public string FullName { get; set; }
15   
16           /// <summary>
17           /// 手机号
18           /// </summary>
19           public string PhoneNumber { get; set; }
20   
21           /// <summary>
22           /// Email
23           /// </summary>
24           public string Email { get; set; }
25   
26           /// <summary>
27           /// 无参构造函数
28           /// </summary>
29           public Employee() { }
30   
31           /// <summary>
32           /// 有参构造函数
33           /// </summary>
34           /// <param name="id"></param>
35           /// <param name="fullName"></param>
36           /// <param name="phoneNumber"></param>
37           /// <param name="email"></param>
38           public Employee(Int64 id, string fullName, string phoneNumber, string email)
39           {
40               this.ID = id;
41               this.FullName = fullName;
42               this.PhoneNumber = phoneNumber;
43               this.Email = email;
44           }
45   
46           /// <summary>
47           /// 获取员工对象集合
48           /// </summary>
49           /// <returns></returns>
50           public static List<Employee> GetEmployeeList()
51           {
52               return new List<Employee>
53               {
54                   new Employee(id:1,fullName:"小强",phoneNumber:"18656678765",email:"xiaoqiang@126.com"),
55                   new Employee(id:2,fullName:"如花",phoneNumber:"15156678765",email:"ruhua@126.com"),
56                   new Employee(id:3,fullName:"玉面小飞龙",phoneNumber:"13856787665",email:"feilong@126.com"),
57                   new Employee(id:4,fullName:"旺财",phoneNumber:"13497747665",email:"wancai@126.com"),
58                   new Employee(id:5,fullName:"来福",phoneNumber:"13908778765",email:"laifu@126.com")
59                };
60           }
61       } 

 

2.创建EmployeeManager.cs的窗体

  界面设计很简单,一个DataGridView控件和两个Button控件,如下:

 

3.创建EmployeeDetail.cs窗体

  这个窗体是用来添加、修改DataTable数据的,对应Employee类几个属性的文本框和确定、取消按钮,设计如下:

整个示例就只有这两个简单的窗体,关键代码在后面给出。

 

4.在内存中创建和Employee类对应的DataTable并添加数据

View Code
 1          /// <summary>
 2          /// 获取Employee表
 3          /// </summary>
 4          /// <returns></returns>
 5          public DataTable GetEmployeeTable()
 6          {
 7              //定义表名称
 8              DataTable empDt = new DataTable("Employee");
 9  
10              //增加列
11              empDt.Columns.Add("ID", typeof(Int64));
12              empDt.Columns.Add("FullName", typeof(string));
13              empDt.Columns.Add("PhoneNumber", typeof(string));
14              empDt.Columns.Add("Email", typeof(string));
15  
16              //定义主键
17              empDt.PrimaryKey = new DataColumn[] { empDt.Columns["ID"] };
18  
19              //增加行数据
20              foreach (Employee oneEmp in Employee.GetEmployeeList())
21              {
22                  //获取一个符合Employee表架构的Row对象
23                  //DataRow oneData = empDt.NewRow();
24  
25                  //oneData["ID"] = oneEmp.ID;
26                  //oneData["FullName"] = oneEmp.FullName;
27                  //oneData["PhoneNumber"] = oneEmp.PhoneNumber;
28                  //oneData["Email"] = oneEmp.Email;
29                  //empDt.Rows.Add(oneData);
30                  empDt.Rows.Add(new object[] { oneEmp.ID, oneEmp.FullName, oneEmp.PhoneNumber, oneEmp.Email });
31              }
32              return empDt;
33          } 

 

5.双击DataGridView任意行时,编辑行数据

View Code
 1          /// <summary>
 2          /// 双击任意单元格发生
 3          /// </summary>
 4          /// <param name="sender"></param>
 5          /// <param name="e"></param>
 6          private void Employee_DataGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
 7          {
 8              if (e.RowIndex == -1) return;
 9              this.btn_delete.Enabled = true;
10  
11              Employee oneEmployee = new Employee();
12  
13              int currentIndex = Employee_DataGrid.CurrentCell.RowIndex;
14              oneEmployee.ID = (Int64)(this.Employee_DataGrid.Rows[currentIndex].Cells[0].Value);
15              oneEmployee.FullName = this.Employee_DataGrid.Rows[currentIndex].Cells[1].Value.ToString();
16              oneEmployee.PhoneNumber = this.Employee_DataGrid.Rows[currentIndex].Cells[2].Value.ToString();
17              oneEmployee.Email = this.Employee_DataGrid.Rows[currentIndex].Cells[3].Value.ToString();
18  
19              //DataRow editRow = (this.Employee_DataGrid.Rows[currentIndex].DataBoundItem as DataRowView).Row;
20              DataRow editRow = (this.Employee_DataGrid.CurrentRow.DataBoundItem as DataRowView).Row;
21  
22              EmployeeDetail detail = new EmployeeDetail(this.EmployeeTable, oneEmployee, editRow, TableAction.Edit);
23  
24              if (detail.ShowDialog() == DialogResult.OK)
25              {
26                  //DataRow oneRow = detail.EmployeeEntry;
27                  //删除成功
28                  MessageBox.Show("修改成功!");
29              }
30          }

 

6.添加删除数据行的代码

 1         /// <summary>
 2         /// 删除数据行
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btn_delete_Click(object sender, EventArgs e)
 7         {
 8             if (Employee_DataGrid.Rows.Count > 0)
 9             {
10                 int currentIndex = Employee_DataGrid.CurrentCell.RowIndex;
11 
12                 DataRow editRow = (this.Employee_DataGrid.CurrentRow.DataBoundItem as DataRowView).Row;
13                 // DataRow editRow = (this.Employee_DataGrid.Rows[currentIndex].DataBoundItem as DataRowView).Row;
14                 if (editRow != null)
15                 {
16                     editRow.Delete();
17                     this.EmployeeTable.AcceptChanges();
18                 }
19             }
20         }

 

7.添加增加数据行的代码

 1         /// <summary>
 2         /// 增加数据行
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btn_Add_Click(object sender, EventArgs e)
 7         {
 8             EmployeeDetail detail = new EmployeeDetail(this.EmployeeTable, TableAction.Add);
 9             if (detail.ShowDialog() == DialogResult.OK)
10             {
11                 DataRow oneRow = detail.EmployeeEntry;
12                 try
13                 {
14                     this.EmployeeTable.Rows.Add(oneRow);
15                     this.EmployeeTable.AcceptChanges();
16                 }
17                 catch (Exception ex)
18                 {
19                     MessageBox.Show("错误:" + ex.Message);
20                 }
21             }
22         }

 

最后我们运行示例程序:

 

增加数据:

 

编辑数据:

 

删除数据:

 

猛击下载:示例源码

作者:晴天猪

出处:http://www.cnblogs.com/IPrograming 

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

posted @ 2012-08-10 21:33  gyzhao  阅读(1659)  评论(3编辑  收藏  举报