DataSet 中的几个重要对象:
TablesCollection 对象: DataSet 里的表用 DataTable 来表示,一个 DataSet 里面可以包含多个 DataTable ,这些 DataTable 就构成了 TablesCollection 对象。每个 DataTable 中都包含一个 ColumnsColleciton 和一个 RowsCollection 对象。
RelationsCollection 对象:各个 DataTable 之间的关系通过 DataRelation 来表达,这些 DataRelation 构成的集合就是 RelationsCollection 对象。
ExtendedProperties 对象:这个对象用来定义特定的信息,比如密码、更新时间等。
1.DataTable 对象
创建 DataTable
DataTable MyTable;
MyTable = new DataTable ("Test");
MyTable.CaseSensitive = False;// 是否区分大小写
MyTable.MinimumCapacity = 100;// 数据库的最小记录空间
创建表的列
DataTable MyTable;
DataColumn MyColumn;
MyTable = new DataTable (" 表名 ");
MyColumn = MyTable.Columns.Add(" 列名 "typeof(string));
MyColumn = MyTable.Columns.Add(" 列名 "typeof(int));
创建表的列示例
// 方法一
DataColumn tax = new DataColumn();
tax.DataType = typeof(Currency);
tax.Expression = "total*rate*0.20";
// 方法二
MyTable.Columns.Add("tax", typeof(Currency), "total*rate*0.20");
2.DataView 对象
DataView 就时数据视图,为数据库结构提供了外模式的实现。同时 DataView 也可以为窗体控件和 Web 控件提供数据绑定功能,在每一个 DataTable 中内建了一个 DataView 为: DataTable.DefaultView()
创建 DataView
DataView sortedView=new DataView(dataTable);
DataView 进行排序:
dataTable.DefaultView.sort="lastName";
dataTable.DefaultView.sort="lastName,FirstName DESC";
DataView 进行筛选和排序:通过 RowFilter 属性设置实现筛选
DataView dv = new DataView(ds.Tables["Authors"]);
dv.RowFilter = "state 'CA'";
dv.Sort = "au_lname";
3.DataColumn 对象示例
DataColumn colCustomerID = dtCustomers.Columns.Add("CustomerId",typeof(Int32));
colCustomerID.AllowDBNull = false;
colCustomerID.Unique = true;
4.DataRow 对象
调用 NewRow 方法来创建一个新的 DataRow 对象
DataRow drNewEmployee = dtEmployees.NewRow();
// 使用索引或列名操作新行
drNewEmployee(0) = 11;
drNewEmployee(1) = "Smith";
// 调用 Add 方法将行添加到 DataRowCollection
dtEmployees.Rows.Add(drNewEmployee);
对行进行批处理更改:
   BeginEdit() 开始更改, EndEdit() 结束更改,同时将更改结果写入 DataSetCancelEdit() ,取消更改
例如:
row.BeginEdit();
row 进行更改
row.EndEdit();
DataTable 中删除 DataRow 对象:
一: DataRowCollection 对象的 Remove 方法示例
DataRow drEmployee = dtEmployees.Rows(3);
dtEmployees.Rows.Remove(drEmployee);
二: DataRow 对象的 Delete 方法示例
drEmployee.Delete;
比较: Remove 方法时从 DataRowCollection 中删除 DataRow ,而 Dalete 方法只是对删除的行做标记。
DataRow 类包括 RowState 属性。 RowState 属性值表示从第一次创建 DataTable (或从数据库加载 DataTable )开始,行是否发生更改,如何更改以及通过何种方式更改。属性的可选值: Modified | Detached | Added
5. 创建表关系示例
// 创建 DataRelation
DataRelation dr;
DataColumn parentCol;
DataColumn childCol;
parentCol = ds.Tables["Customers"].Columns["CustomerID"];
childCol = ds.Tables["Orders"].Columns.["CustomerID"];
dr = new DataRelation("CustOrders", parentCol, childCol);
ds.Relations.Add(dr);
currentParentRow = ds.Tables["Customers"].Rows[DataGridName.SelectedIndex];
foreach(DataRow r in currentParentRow.GetChildRow("CustOrders"))
{
   Lable1.Text += r["OrderID"] + ",";