關於GridView使用學習總結

來源:瑞文範文網 1.78W

由於視頻比較舊,涉及到的數據綁定控件DataGrid在VS20xx中已經沒有了,取而代之的是GridView。開始覺得視頻中的例子沒法實現了,其實不然,DataGrid裏面的功能GridView裏一樣都不少,只是形式變化了一下,仔細研究一下發現它們是換湯不換藥啊。

關於GridView使用學習總結

(一)DataKeyName屬性

(1)DataKeyNames一般都是用來對當前行做唯一標示的,所以一般爲數據庫的ID。

(2)Keys[ndex],ndex是獲取事件對應的行,Keys[ndex]就是獲取對應行的唯一標示也就是DataKeyNames所指定列的值。

(3)DataList和Repeater是沒有的該屬性的。

在代碼中這樣使用:(定義的該函數在下面都需要調用)

/// 實現數據綁定功能 ///

private void BindToDataGird { SqlConnection con = teCon; SqlDataAdapter sda = new SqlDataAdapter; ctCommand = new SqlCommand("select employeeID,FirstName,LastName,Title,BirthDate from employees ", con); DataSet ds = new DataSet; (ds, "emp"); //將查詢到的數據添加到DataSet中。 KeyNames =new string{ "employeeID"}; //DataKeyNames的使用 Source = es["emp"]; Bind; }

如何取值?

DataKey key = Keys[ndex];//其中e爲GridViewDelete(或者Edit)EventArgs e string empID = key[0]ring;

(二)分頁

由於GridView中封裝了分頁的功能。這裏實現起來很容易。先需要設置屬性:AllowPaging/PageSize/PageSetting。然後編寫事件代碼:

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { Index = ageIndex; ToDataGird; }

(三)排序

首先設置AllowSorting屬性爲true.事件代碼:

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { if (ViewState["order"] == null) //使用ViewState設置雙向排序。 { ViewState["order"] = "ASC"; } else { if (ViewState["order"]ring == "ASC") { ViewState["order"] = "DESC"; } else { ViewState["order"] = "ASC"; } } //數據綁定顯示 SqlConnection con = teCon; SqlDataAdapter sda = new SqlDataAdapter; ctCommand = new SqlCommand("select employeeID,FirstName,LastName,Title,BirthDate from employees ", con); DataSet ds = new DataSet; (ds, "emp"); es["emp"] = Expression + " " + ViewState["order"]ring; //設置排序 Source = es["emp"]ultView; //將表的默認視圖作爲數據源。 Bind; }

(四)刪除

這裏需要注意一點:就是獲取某一行的主鍵值。

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { DataKey key = Keys[ndex]; string empID = key[0]ring; SqlConnection con = teCon; SqlCommand cmd = new SqlCommand(" from employees where employeeID= +empID+" , con); ; uteNonQuery; ToDataGird; }

(五)編輯(更新和取消)

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { Index = ditIndex; ToDataGird; } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { Index = -1; //設置索引值爲負取消編輯。 ToDataGird; } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { DataKey key = Keys[ndex]; string empID = key[0]ring; string lastName=((TextBox)( [ndex ] s [2]rols [0])) ; //將GridView中某列中控件強制轉換爲TextBox,然後取出它的值。 e(empID +"&" + lastName ); //用於測試。 Index = -1; ToDataGird; }

熱門標籤