DataGrid entry classic
Author: wyhw Time: 2003-5-11 Recommended Level: ★ View author information and author anthology
How to implement editing, deletion, category, and paging operations in the DataGrid control: http://www.c-sharpcorner.com/asp/code/northwindlc.asp Preface: This article mainly describes how to implement editing in the DataGrid control , Delete, classify, and page operations. To achieve our intention, we use the Northwind database that comes with SQL Server2000. The program is divided into two parts: 1. Contains the HTML code .aSPX file 2. Contains the background C # class file code containing all logic and methods: ASPX file: Here we have designed a DataGrid object, I have an annotation for some attributes and methods .
It becomes such a simple:
// This event activates myDataGrid_edit function (function) Edit a record autogeneratecolumns = "false" // Setting automatic behavior "false" horizontalalign = "left"> FooterStyle> HeaderStyle> PagerStyle> SelectedItemStyle> itemStyle> asp: edtcommandcolumn> asp: butt onColumn> asp: BoundColumn>
"ProductName" HeaderText = "ProductName"> asp: BoundColumn> asp: BoundColumn> asp: BoundColumn> < / asp: BoundColumn> asp: BoundColumn> asp: BoundColumn> itemtemplate> asp: templatecolumn> c Olumns> ask: DataGrid> Do you see, is it not difficult? The key is that we are moving through the brain. It is also very important to see more information! C # Background Program: Let us first see a program: private void page_load (Object sender, system.eventargs e) {if (! Ispostback) {bindgrid ();}} The above is a very good technology, when the page is not The data is bound when the Postback status is. This means that once the page is requested to be binded.
Continue to see the program: /// /// This function returns DataSet /// summary> /// returns> private dataset getProductData () {// sqlstatement is a SQL statements (string type) string SQLStatement = "SELECT Products.ProductID, Products.ProductName, Products.QuantityPerUnit, Products.UnitPrice," "Products.UnitsInStock, Products.UnitsOnOrder, Products.ReorderLevel, Products.Discontinued" "FROM PRODUCTS ";: /// Declaring SQLConnection object: myconnection sqlconnection myconnection = new sqlconnection (@" server = (local) / netsdk; " " Database = northwind; uid = northwind; "); ////// statement command object: myCommand SqlDataAdapter myCommand = new SqlDataAdapter (SQLStatement, myConnection); /// set command type command type Text myCommand.SelectCommand.CommandType = CommandType.Text; /// to create an object instance DataSet myDataSet = new DataSet (); /// Pack the data returned from the table products (MyDataSet, "Products"); /// Finally returns the MyDataSet object return myDataSet;} This code performs a given SQL statement to access the database, private functions GetProductData returns a DataSet that contains data records. Next, let's see how to edit the record: /// /// This function will only be activated when the user clicks the Edit button is /// summary> /// < / param> /// param> protected void myDataGrid_edit (object sender, DataGridCommandEventArgs e) {// identification index (ItemIndex), and further bind data MyDataGrid. EdititeMindex = (int) E.Item.itemindex; bindgrid ();} You can also understand the function of myDataGrid_edit function by clicking the EDIT button, and the program finds the record you want to edit when the user clicks on the Edit button. The index is assigned to the DataGrid's EditIndex property.
If the user clicks on the Cancel button, we will call the MyDataGrid_cancel function mentioned above. If the value assigned to the DataGrid property EditItemIndex is -1, it means that the user does not select Edit, the program is as follows: /// < Summary> /// User Click the CANCEL button to activate the MyDataGrid function //// summary> /// param> /// param> protected void MyDataGrid_cancel (Object Sender, DataGridCommandeventAndArgs E) {MyDataGrid.editItemIndex = -1; bindgrid ();} The following code shows how to delete a selected record from the DataGrid. We know that the Web Control DataGrid has a DatakeyField property, in fact it contains the ProductID field value of each record.
You must ask how to get the productID value recorded in the DataGrid through the DataKeyField property? The following code will let you relieve: ----- int products = (int) mydatagrid.datakeys [(int) E.Item.itemindex]; ----- MyDataGrid_delete function code as follows: /// /// Remove a record from DataSet /// summary> /// param> /// param> protected void myDataGrid_delete (Object sender, DataGridCommandEventArgs E) {int ProductID = (int) MyDataGrid.DataKeys [(int) E.Item.ItemIndex]; string SQLStatement = "Delete Products WHERE ProductID =" ProductID; string myConnectionString = "server = localhost; uid = sa; pwd =; database = NorthWind "; SqlConnection myConnection = new SqlConnection (myConnectionString); SqlCommand myCommand = new SqlCommand (SQLStatement, myConnection); myCommand.CommandTimeout = 15; myCommand.CommandType = CommandType.Text; try {myConnection.Open (); MyCommand.executenonQuery (); MyConnection.Close ();} catch (exception ee) {throw ee;} mydatagrid.edititeMindex = -1; bindgrid ();} The following code is used to update product information of the Northwind database, we can use the following technology to retrieve values : ----------------- Bool discon = (CheckBox) E.Item.FindControl ("discontinued")). Checked; --------- ---------- When we use the FinControl () method to get the value of Discontinue CHECKBOX. /// /// update record /// summary> /// <
param name = "sender"> param> /// param> protected void MyDataGrid_Update (Object sender, DataGridCommandEventArgs E) {int ProductID = (int) MyDataGrid.DataKeys [(int) E.Item.itemindex]; String ProductName = ((TextBox) E.Item.cells [3] .controls [0]). TEXT; STRING QuantityPerunit = ((TextBox) E.Item.cells [4] .controls [0 ]). TEXT; STRING UNITPRICE = ((TextBox) E.Cells [5] .controls [0]). Text; INT16 UnitsStock = Int16.Parse ((TextBox) E.ITEM.Cells [6] .controls [0]); INT16 Unitsonorder = INT16.PARS ((TextBox) E.Item.cells [7] .controls [0]). Text); INT16 REORDERLEVEL = INT16.PARSE ((TextBox) e. Item.cells [8] .controls [0]). TEXT); BOOL Discon = ((CheckBox) E.Item.FindControl ("discontinued")). Checked; int result; if (! Discon) {result = 0; } Else {result = 1;} string SQLStatement = "UPDATE Products" "SET ProductName = '" ProductName "'," "QuantityPerUnit = '" QuantityPerUnit "'," "UnitPrice =" UnitPrice.Substring (UnitPrice.IndexOf ( "¥") 1) "," "UnitsStock =" UnitsInsTock "," "Unitsonorder =" Unitsonorder "," "REORDERLEVEL =" REORDERLEVEL "," "
"Discontinued =" result "WHERE ProductID =" ProductID; string myConnectionString = "server = localhost; uid = xjb; pwd = xjb; database = Northwind"; SqlConnection myConnection = new SqlConnection (myConnectionString); SqlCommand myCommand = new SqlCommand ( SQLStatement, myConnection); myCommand.CommandTimeout = 15; myCommand.CommandType = CommandType.Text; try {myConnection.Open (); myCommand.ExecuteNonQuery (); myConnection.Close ();} catch (Exception ee) {throw ee;} MyDataGrid.edititemindex = -1; bindgrid ();} The next bindgrid () calls the private function GetProductData acquires the DataSet object and binds to the DataGrid control. /// /// accept database data and binds /// summary> protected void bindgrid () {MyDataGrid.dataSource = getProductData (). Tables ["Products"]. defaultview; mydatagrid.databind (MYDATAGRID.DATABIND );} The user activates myDataGrid_pageIndexchanged events during DataGrid, because DataGrid cannot automatically obtain the index number of the new page, so we can only get the index number manually. /// /// Page Operation /// Summary> /// param> /// param> protected void MyDataGrid_pageIndexchanged (Object Source, DataGridPageChangeDeventargs E) {MyDataGrid.currentpageIndex = E.NewpageIndex; bindgrid ();} User When you want to classify the data, the following Sort_Grid events are activated.