DataGrid basic knowledge

xiaoxiao2021-03-05  23

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 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 has become so simple: program code: [Copy code to clipboard]

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 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 statement (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: myConnection SqlConnection myConnection = new SqlConnection (@" server = (local) / NetSDK; " " database = NorthWind; uid = northwind ; pwd = northwind; "); /// command object declaration: myCommand SqlDataAdapter myCommand = new SqlDataAdapter (SQLStatement, myConnection); /// set command type command type Text myCommand.SelectCommand.CommandType = CommandType.Text; // / Create a DataSet object instance MyDataSet = new dataset (); /// Pack the data returned from the table products fills myData mycommand.fill (MyDataSet, "Products"); /// Finally returns the MyDataSet object return myDataSet;} This code is executed A given SQL statement accesses the database, and the private function getProductData returns a DataSet that contains data records. Next, let's see how to edit the record: ///

/// This function is only activated when the user clicks the Edit button. /////

///

Protected void mydatagrid_edit (Object sender, DataGridCommandeventArgs e) {// identify the index (ItemIndex) of the selected item, and further bind data myDataGrid.edititeMindex = (int) E.Item.itemindex; bindgrid ();} through The annotation of the above code can also understand the function of myDataGrid_edit function: activate myDataGrid_edit functions when the user clicks the Edit button, and the program finds the index of the record you want to edit, assign the index number to the DataGrid's edititeMindex property. If the user clicks on the Cancel button, we will call the MyDataGrid_cancel function mentioned in the above .aspx file, 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: //// / / Activate the MyDataGrid function / / //// / / /

///

Protected Void MyDataGrid_cance (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 the 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 (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 the Northwind database Product information, we can use the following technology to search the value: ----------------- Bool discon = (Checkbox) E.Item.FindControl ("discontinued")) .Checked; ------------------ This time we use the FinControl () method to get the value of Discontinued Checkbox. ///// update record /// / //

///

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.Cells [4] .controls [0]). Text; String Unitprice = ((TextBox) E.Cells [5] .controls [0]) .Text; INT16 UnitsStock = INT16.PARS ((TextBox) E.cells [6] .controls [0]). Text); INT16 Unitsonorder = Int16.Parse ((TextBox) E.Item.cells [7 ] .Controls [0]). Text); INT16 REOREDERLEVEL = INT16.PARS ((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 " " " Unitprice = " Unitprice.substring (Unitprice.Indexof (" ¥ ") 1) ", " " UnitsNstock = " ", " " "Unitsonorder =" Unitsonorder "," "REORDERLEVEL =" REORDERLEVEL "," "Discont inued = " 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 gets the DataSet object and tied Set to the DataGrid control. ///// accept database data and bind /// protected void bindgrid () {myDataGrid.datasource = getProductData (). Tables ["Products"]. Defaultview; mydatagrid.databaseD ();} User in DataGrid Amused the MyDataGrid_pageIndexchanged event when moving forward or back, because DataGrid cannot automatically get 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 ();} when the user wants to classify the data, the following Sort_Grid event is activated at any time. 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. ///

/// Category /// ///

///

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-38199.html

New Post(0)