How to implement editing, delete, classify, and paginity in the DataGrid control

zhaozj2021-02-16  101

How to implement editing, delete, classify, and paginity in the DataGrid control

Www.chinacs.net 2001-9-13 Chinese C # Technology Station

Article Source: http://www.c-sharpcorner.com/asp/code/northwindlc.asp

Preface:

This article mainly describes how to implement editing, delete, classify, and paginize operations in a DataGrid control. To achieve our intention, we use the Northwind database that comes with SQL Server2000. The program is divided into two parts:

1. Contains an .aspx file with HTML code

2. Contains background C # class files for all logic and methods

Code:

ASPX file:

Here we designed a DataGrid object, I have an annotated for some attributes and methods. It has become so simple:

BorderStyle = "ridge"

Gridlines = "none"

BorderWidth = "2px"

Bordercolor = "White"

Backcolor = "White"

Cellpadding = "3"

Cellspacing = "1"

ALLOWPAGING = "True" // allowpaging property "TRUE", you can make a pagination operation

ALLOWSORTING = "true" // This is a classified property

PageSize = "15" // Set 25 records per page

PagersTyle-mode = "nextprev" // There are 2 models: Next Previous and Page Numberin

PagersTyle-nextpagetext = "next"

Pagerstyle-prevpagetext = "previous"

Pagerstyle-horizontalalign = "center"

Pagerstyle-position = "topandbottom"

DataKeyField = "ProductID" // DataGrid each record contains a productID field

ONPAGEINDEXCHANGED = "MyDataGrid_pageIndexchange // activates myDataGrid_pageIndexchanged function when the user performs page operation.

OnSortCommand = "sort_grid" // activates the sort_grid (function) function when the user is classified for the DataGrid classification

OndeleteCommand = "mydataGrid_delete" // This event activates myDataGrid_delete functions (function) delete a record

OnupdateCommand = "mydataGrid_update" // This event activates the MyDataGrid_Update function (Function) update a record

Oncancelcommand = "MyDataGrid_cancel // This event activates myDataGrid_cancel function (function) cancels the current operation

OneDitCommand = "MyDataGrid_edit" // This event activates myDataGrid_edit function (function) Edit a record autogeneratecolumns = "false" // Settings Automatic behavior "false"

Horizontalalign = "Left">

Position = "topandbottom" Backcolor = "# c6c3c6">

Sortexpression = "discontinued"> 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 /// /// 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 ";: /// SqlConnection object declaration: myConnectionSqlConnection myConnection = new SqlConnection (@" server = (local) / NetSDK; " " database = NorthWind; uid = northwind; pwd = northwind; "); /// Command statement 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 Table Products (MyDataSet, "Products"); /// Finally returns a MyDataSet object return mydataset;} This code performs a given SQL statement to access the database, private functions getProductData return one Contains data recorded DataSet.

Next, let's see how to edit the record: ///

/// This function will only be activated when the user clicks the Edit button is /// /// < / 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 //// /// /// 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 /// /// /// 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; 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 Northwind Database product information, we can use the technical search value: ------------------ Bool discon = ((CheckBox) E.Item.FindControl ("discontinued" )). Checked; ------------------ then we can get the value of discontinued checkbox using the FinControl () method. ///

/// update Record /// /// /// protected void myDataGrid_update (Object sender, DataGridCommandEventArgs e) {int ProductId = (int) mydatagrid.datakeys [(int) E.Item.itemindex]; string productName = ((textbox) E.cells [3] .controls [0]). Text; string quantityperunit = ((TextBox) E.Item.cells [4] .controls [0]). TEXT; STRING UNITPRICE = ((TextBox) E.ITEM.Cells [5] .controls [0]). TEXT; INT16 UnitsStock = Int16.Parse TextBox) E.Item.cells [6] .controls [0]). Text); 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 =" "UnitsNoscock ", " " 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.executenonury (); myconnection.close ();} catch (exception ee) {throw ee;}

MyDataGrid.editIndex = -1; bindgrid ();

The next BindGrid () calls the private function GetProductData to get the DataSet object and bind to the DataGrid control. ///

/// accept database data and binds /// 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 /// /// /// 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. For example, if a user clicks Field Headers, the event will be activated and divide the data into the classification we want. We need a DataView object to classify the E.Sortexpression.toString () method, returned to the category of the domain title. /// /////// /// /// protected void sort_grid (Object sender, DataGridSortCommandEventArgs e) {DataView dv = new DataView (GetProductData () Tables [ "Products"].); dv.Sort = e.SortExpression.ToString (); MyDataGrid.DataSource = dv; MyDataGrid.DataBind (); }

转载请注明原文地址:https://www.9cbs.com/read-10551.html

New Post(0)