Batch update the rows bound to the gridview Web Server Control (edit all rows at the same time)

Source: Internet
Author: User

Http:// (V = vs.80). aspx

Create a website

If you have completed the drill: Create a base page in visual web developer and create a website in Visual Web Developer, you can use the website and go to the next section. Otherwise, follow the steps below to create a new website and webpage.

Create a file system website
  1. Open visual web developer.

  2. On the File menu, click New, and then click website ". If you are using a quick version of Visual Web Developer, click New website on the File menu ".

    The new website dialog box appears.

  3. Under Visual Studio installed templates, click ASP. NET Website ".

  4. Click File System in the location list, and enter the name of the folder to save the website webpage.

    For example, enter a folder name."C: \ websites \ bulkupdate".

  5. In the language list, click the expected programming language.

  6. Click OK ".

    Visual Web Developer creates this folder and a new page named default. aspx.

Add a data source for the gridview Control

To display data on an ASP. NET webpage, you need the following elements:

  • Connect to a data source (such as a database.

    In the following process, you will create a connection to the SQL Server northwind database.

  • On this page, a data source control is used to interact with the data source (database) to read and write data.

  • The control that displays data on this page.

In the following processGridviewControl display data.GridviewTheSqldatasourceControl.

Add a data source for the gridview Control
  1. Open or switch to the default. aspx page.

  2. Switch to the design view.

  3. From the data tab of the toolboxSqldatasourceDrag the widget to the page.

    If the "sqldatasource task" Smart tag is not displayed, right-clickSqldatasourceControl, and then click show Smart Tag ".

  4. On the sqldatasource task panel, click Configure data source ".

    The "configure data source" Wizard appears.

  5. Click Create connection ".

    The "add connection" dialog box appears.

  6. If necessary, Perform one of the following operations: the specific user interface you see depends on the data connection you created in visual web developer.

    • If "Microsoft SQL Server (sqlclient)" is not displayed in the "Data Source" list, click "change" and select "Microsoft SQL Server" in the "Change Data Source" dialog box ".

    • If the "Select data source" dialog box appears instead of the "Connection Properties" dialog box, select the data source type to use in the "Data Source" list. In this walkthrough, the data source type is "Microsoft SQL Server ". In the data provider list, click. NET Framework data provider for SQL Server, and then click Continue ".

  7. In the "server name" text box on the "add connection" Page, enter the name of the computer that runs the SQL Server northwind database.

  8. Under "log on to server", select the appropriate option to access the SQL Server database (integrated security or specific ID and password ). If necessary, enter the user name and password.


    If you need information about how to log on to the computer that runs SQL Server, contact the server administrator.

  9. If you have entered a password, select the "Save Password" check box.

  10. Click Select or enter a database name, and then enter"Northwind".

  11. Click test connection, and click OK after the connection is confirmed to take effect ".

  12. In the "configure data source" Wizard, click "Next ".

  13. Make sure that the "yes, save this connection as" check box is selected.

  14. Name the connection"Northwindconnectionstring"And then click "Next ".

  15. On the "Configure SELECT statement" Page, select "specify columns from tables or views ".

  16. In the "name" list, select"Employees".

  17. Under "column", select"Employeeid","Titleofcourtesy","Lastname","Firstname","Title"And"Extension".

  18. Click "advanced ".

  19. Select the "generate insert, update, and delete statements" check box, and click "OK ".

  20. Click "Next ".

  21. Click Finish ".

Add a gridview Control for displaying data

After configuring the data source control for data management, you also need a control for displaying data on this page.

In the following processGridviewControl display data.GridviewControl will be added fromSqldatasourceControl.

To enable the user to edit allGridviewControl content (instead of editing only one row at a time), must be customizedGridviewControl. You replace the default display elements in each column with editable elements, and then bind them to the data source. To complete this operation, you will create the templatefield column. In eachTemplatefieldA bound Textbox Control is added to the itemtemplate of a column. You can edit data in the control.

Add and configure the gridview Control for displaying data
  1. Make sure that you are in the design view on the default. aspx page.

  2. Drag a gridview control from the data tab of the toolbox to the page.

    In the "Select data source" list box on the "gridview task" Panel, selectSqldatasourceWidget"Sqlperformance1".

  3. Select enable paging ".

  4. Click Edit column ".

    The "field" dialog box appears.

  5. Under "selected fields", select "titleofcourtesy ".

  6. Click "convert this field to templatefield ".

  7. Use and previous Conversion"Titleofcourtesy"If the fields are the same"Employeeid"Convert other fields other than fields to template fields. ("Employeeid"The field contains the primary key and cannot be edited .)

  8. Click OK ".

  9. On the "gridview task" Panel, click "Edit template ".

  10. Under titleofcourtesy in the displayed list, click edititemtemplate ".

    GridviewThe control displays an editable area, and the default layout of the titleofcourtesy column is in editing mode.

  11. Right-click edititemtemplateTextboxControl, and then click Copy ".

  12. Right-clickGridviewControl, and then click show Smart Tag ".

  13. Under titleofcourtesy in the displayed list, click itemtemplate ".

    GridviewThe control now displays the default layout of the "titleofcourtesy" column in display mode.

  14. Delete an existing label control.

  15. Right-click the "itemtemplate" editable area and click "Paste ".

    You haveTextboxControl (including the data binding configuration of the Control) fromEdititemtemplateCopy layoutItemtemplateLayout.

  16. SelectTextboxControl, and in the "properties" window, set the "(ID)" attributeTitleofcourtesytextbox.

  17. Set the "maxlength" attribute25(Maximum length of fields in the database ).

    This ensures that the information entered by the user does not exceed"Titleofcourtesy"Field capacity.

  18. Repeat the preceding seven steps for each template field and copyTextboxReplace existingLabelControl, and set the ID attribute<Data field Name>Textbox.

    For eachTextboxThe maxlength attribute of the Control. Use the following values.

    • Firstname: 10

    • Lastname: 20

    • Title: 30

    • Extension: 4

  19. Right-clickGridviewControl, and then click "End template editing ".

Add and execute batch update process

Configured to display editable dataGridviewAfter the control, you need to add the code for executing batch update. This Section performs the following tasks:

  • Add the button control andClickAdd code to the handler to updateGridviewControls.

  • Add a able object to store original data values.

  • Add the code used to determine whether the row is modified.GridviewThe current value displayed inDatatableCompare the original values in the object. If one or more displayed values do not match the original values, the row is updated in the database. Otherwise, this row is not included in batch update.

Create and execute batch update process
  1. Switch to the design view.

  2. SelectGridviewControl, and click the event button () in the "properties" window to displayGridviewControls.

  3. In the rowdatabound field, Type"Gridviewdomainrowdatabound"And press Enter.

    Visual Web DeveloperGridviewControlRowdataboundCreate an event handler for an event. The code is similar to the following code example.

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e){}
  4. Use the following code (including private variables) to replace the generated process.

    private bool tableCopied = false;private DataTable originalDataTable;protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e){    if (e.Row.RowType == DataControlRowType.DataRow)        if (!tableCopied)        {            originalDataTable = ((DataRowView)e.Row.DataItem).Row.Table.Copy();            ViewState["originalValuesDataTable"] = originalDataTable;            tableCopied = true;        }}

    As longGridviewControl to run the data binding. When binding the first line, the codeDatatableThe object stores a copy of the original database value, and the object is stored in viewstate.

  5. Switch to the design view.

  6. Drag a button control from the "standard" tab of the toolkit to the page.

  7. In the Properties window, click the Properties button () to displayButtonControls.

  8. In the "(ID)" field, enter"Updatebutton".

  9. In the text field, enter"Update".

  10. Click the event button () to displayButtonControls.

  11. In the "click" field, Type"Updatebutton_click"And press Enter.

    Visual Web DeveloperButtonClick Event of the control to create an event handler. The code is similar to the following code example.

    protected void UpdateButton_Click(object sender, EventArgs e){}
  12. Replace the Generated Process with the following code.

    protected void UpdateButton_Click(object sender, EventArgs e){    originalDataTable = (DataTable)ViewState["originalValuesDataTable"];    foreach (GridViewRow r in GridView1.Rows)        if (IsRowModified(r)) { GridView1.UpdateRow(r.RowIndex, false); }    // Rebind the Grid to repopulate the original values table.    tableCopied = false;    GridView1.DataBind();}protected bool IsRowModified(GridViewRow r){    int currentID;    string currentTitleOfCourtesy;    string currentLastName;    string currentFirstName;    string currentTitle;    string currentExtension;    currentID = Convert.ToInt32(GridView1.DataKeys[0].Value);    currentTitleOfCourtesy = ((TextBox)r.FindControl("TitleOfCourtesyTextBox")).Text;    currentLastName = ((TextBox)r.FindControl("LastNameTextBox")).Text;    currentFirstName = ((TextBox)r.FindControl("FirstNameTextBox")).Text;    currentTitle = ((TextBox)r.FindControl("TitleTextBox")).Text;    currentExtension = ((TextBox)r.FindControl("ExtensionTextBox")).Text;    DataRow row =        originalDataTable.Select(String.Format("EmployeeID = {0}", currentID))[0];    if (!currentTitleOfCourtesy.Equals(row["TitleOfCourtesy"].ToString())) { return true; }    if (!currentLastName.Equals(row["LastName"].ToString())) { return true; }    if (!currentFirstName.Equals(row["FirstName"].ToString())) { return true; }    if (!currentTitle.Equals(row["Title"].ToString())) { return true; }    if (!currentExtension.Equals(row["Extension"].ToString())) { return true; }    return false;}

    This process uses each editableTextboxThe value in the control and the cachedDatatableThe values stored in the object are compared to strings. IfTextboxIf the text in the control is formatted, its values may be the same, but its string representation does not match. For example, if you set the datetime value format to the short Date Format
    ({0: d}), Then the dateTextboxThe value in the control may be3/2/2005. WhileDatatableThe string representation of the date value in the object isAM. In these cases, the comparison logic must be added to take the format and localization settings into account.

    This process cyclically accessesGridviewControls, and CALLS customIsrowmodifiedFunction. This function maps the current rowDatatableCompare the corresponding rows in the object, and if the row is changed, returnTrue. For any row that has been changedClickThe code in the handler will callGridviewThe updaterow method of the control.

Test page

Now you can run the page to test the code.

Test the page
  1. Press Ctrl + F5 to run the page.

    This page is displayed in the browser.GridviewThe control displays the data rows in the northwind employees table in the form of an editable data page.

  2. Modify some values.

  3. Click Update ".

    The modified row is updated in the database.

  4. Close your browser.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.