標籤:ado.net
1 DataColumn 的DataType可以是任一資料類型,包括自義定類和結構.
DataTable dt = new DataTable("Product"); dt.Columns.Add("ProductId",typeof(int)); dt.Columns.Add("ProductProperty", typeof(ProductProperty)); DataRow r1 = dt.NewRow(); r1["ProductId"] = 1; r1["ProductProperty"] = new ProductProperty() { ProductionDate = DateTime.Now, Desc = "牛奶糖" }; dt.Rows.Add(r1); foreach(DataRow dr in dt.Rows) { Console.WriteLine("productId {0};ProductionDate:{1};Desc:{2};", dr["ProductId"].ToString(), (dr["ProductProperty"] as ProductProperty).ProductionDate.ToString(), (dr["ProductProperty"] as ProductProperty).Desc); }
2 Unique屬性標記為True 的DataColumn 不請允許有NULL值.
3 判斷DataRow中某個列是否已經修改
//oneRow.DataRowState=DataRowState.Changed,否則可能沒有Original版本if(oneRow.HasVersion(DataRowVersion.Proposed)){ if(oneRow["Salary",DataRowVersion.Original]!=oneRow["Salary",DataRowVersion.Proposed]) { //salary field has changed }}
4 使用DataRow.BeginEdit() DataRow.EndEdit() 延遲資料驗證,同時減少RowChanged事件觸發次數
oneRow.BeginEdit();oneRow["ProductName"]="ColaVeryGood";//ProductName MaxLength 為10oneRow["UnitPrice"]=12.4;//UnitPrice 最大值為 10.0oneRow.EndEdit();//直到此時才發生資料驗證異常,如果沒有異常,則發生RowChanged事件,而不會觸發兩次事件.
5 基於驗證的錯誤
利用DataColumnChanging,DataRowChanging,可以修改的資料進行驗證,防止不符合驗證程式的資料輸入到欄欄位或提示出資料不合法.
private void app_ColumnChanging(object sender,DataColumnChangeEventArgs e){ if(e.Column.ColumnName=="Age") { if((int)e.ProposedValue>120) e.Row.SetColumnError(e.Column,"Human can‘t live that long"); } }
6 列層級的錯誤
public void ShowFirstRowError(DataRow row){ string errorText = "No error!"; DataColumn[] errorColumns = row.GetColumnsInError(); if(errorColumns.Count>0) { errorText= row.GetColumnError(errorColumns[0]); } else if(row.RowError.Length>0) { errorText = row.RowError; } // show errorText}
7 按主鍵搜尋行
DataRow matchRow = someTable.Rows.Find(searchValue);//single-part keyDataRow matchRow = someTable.Rows.Find(new object[]{value1,value2})//multi-Part key;//如果未找到行,返回null
8 用搜尋條件選擇行及排序
//匹配字條串時區分大小寫//someTable.CaseSensitive=True;//預設不區分大小寫DataRow[] matchRows = someTable.Select(filterCriteria,sortRules);//filterCriteria 過濾運算式參考 DataColumn.Expression 很強大//sortRules OrderDate DESC,CustomerName ASC,ASC是預設排序,可省略.
本文出自 “智壘天下” 部落格,請務必保留此出處http://chenwan.blog.51cto.com/2754591/1567286
ADO.NET知識點筆記