ADO.NET:DataSet對象詳解

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"] + ",";
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章