ADO.NET常用对象详解之:DataSet对象

 
在ADO.NET中DataSet的作用是为数据源提供一个断开式的存储,而不必关心数据源,操作只用在DataSet中进行就行了。
创建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";
示例
DataColumn colCustomerID = dtCustomers.Columns.Add("CustomerId",typeof(Int32));

colCustomerID.AllowDBNull
= false;
colCustomerID.Unique
= true;
创建DataRow对象
DataRow drNewEmployee = dtEmployees.NewRow();

//使用索引或列名操作新行
drNewEmployee(0) = 11;
drNewEmployee(
1) = "Smith";

//调用Add方法将行添加到DataRowCollection中
dtEmployees.Rows.Add(drNewEmployee);

对行进行批处理更改:
   BeginEdit()开始更改,EndEdit()结束更改,同时将更改结果写入DataSet,CancelEdit(),取消更改
例如:
row.BeginEdit();
对row进行更改
row.EndEdit();

从DataTable中删除DataRow对象:
一:DataRowCollection对象的Remove方法

示例
DataRow drEmployee = dtEmployees.Rows(3);
dtEmployees.Rows.Remove(drEmployee);
示例
drEmployee.Delete;
示例
//创建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"] + ",";
}
示例一
GridView.DataSource = ds;
GridView.DataMember
= "Authors";
GridView.DataBind();
示例二
GridView.DataSource = ds.Tables["Authors"];
GridView.DataBind();
示例三
DataView dv = new DataView(ds.Tables["Authors"]);
dv.RowFilter
= "state = 'CA'";
GridView.DataSource
= dv;
GridView.DataBind();
posted @ 2008-05-02 11:03  chunchill  阅读(442)  评论(0编辑  收藏  举报