Author: Unknown author please contact me speed
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:
Code copy box
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"> pageerstyle> Itemtemplate> asp: templateColumn> Columns> ask: DataGrid> [Ctrl A All Choose and Copy] Do you see it, isn't it 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 show is a very good technology that binds the data when the page is not a Postback status. This means that once the page is requested to be binded. Continue to see the program: Code copy box /// /// This function returns DataSet about product details /// summary> /// Private Dataset getProductData () { /// sqlStatement is a SQL statement (String type) String SqlState = "Select Products.ProductID, Products.ProductName, Products.quantityPerunit, Products.Unitprice," "Products.UnitsInStock, Products.Unitsonorder, Products.Reorderlevel, Products.Discontinued" "From product"; /// Declare SqlConnection object: MyConnection SqlConnection MyConnection = New SqlConnection (@ "server = (local) / netsdk;" Database = northwind; uid = northwind; pwd = northwind; "); /// Declaration Command object: MyCommand SqlDataAdapter myCommand = New SqldataAdapter (SqlStatement, MyConnection); /// Set the type of command command to text type Mycommand.selectcommand.commandtype = commandType.Text; /// Create a DataSet object instance MyDataSet = new dataset (); // / Pack the data returned from the table products MYDATA MyCommand.Fill (MyDataSet, "Products"); /// finally returns myDataSet object Return mydataset; } [Ctrl A All Choose and Copy] This code performs a given SQL statement to access the database, and the private function getProductData returns a DataSet that contains data records. Next, let's see how to edit the record: Code copy box /// /// This function is only activated when the user clicks the Edit button. /// summary> /// /// Protected void myDataGrid_edit (Object Sender, DataGridCommandeventArgs E) { // / identify the index of the selected item (ITEMINDEX) and further bind data MyDataGrid.edititeMindex = (int) E.Item.ItemIndex; Bindgrid (); } [Ctrl a All Choice and then copy] If you commented by the above code, you can also understand the function of myDataGrid_edit function: activate the MyDataGrid_edit function when the user clicks the Edit button, and the program finds the index of the record you want to edit, assign the index number Give 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: Code copy box / // /// summary> /// /// Protected Void MyDataGrid_cancel (Object Sender, DataGridCommandeventArgs E) { MyDataGrid.edititemindex = -1; Bindgrid (); } [Ctrl A All Choose and Copy] 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: code copy box ----- INT productID = (int) MyDataGrid.dataKeys [(int) E.Item.itemindex]; ----- MyDataGrid_delete function code is 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 SqlState = "delete products where produter =" 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 (); } [Ctrl A All Choose and Copy] The following code is used to update product information of the Northwind database, we can use the technical search value: ----------------- Bool discon = ((Checkbox) e. Item.FindControl ("discontinued")). Checked; ------------------- At this time we use the FinControl () method to get the value of DiscontinueD Checkbox. Code Copy box /// ///update record /// summary> /// 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]). String QuantityPerunit = ((TextBox) E.Item.cells [4] .controls [0]). String unitprice = ((TextBox) E.Item.cells [5] .controls [0]). TEXT; INT16 UnitsStock = INT16.PARS ((TextBox) E.Cells [6] .controls [0]). Text); INT16 Unitsonorder = INT16.PARS ((TextBox) E.centm.cells [7] .controls [0]). TEXT); INT16 REORDERLEVEL = INT16.PARS ((TextBox) E.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) "," "UnitsInstock =" 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 (); }