Export (0) Print
Expand All

Walkthrough: Using a DataGrid Web Control to Read and Write Data

Visual Studio .NET 2003

The architecture of Web Forms data binding makes it easy to display data in page controls. However, data binding is not two-way — that is, data binding reads data from a data source but does not update it. Updating is more complex than displaying data, and because the majority of Web Forms pages do not require that data be written back to the source, Web Forms data binding keeps page sizes and page processing to a minimum by not including update code.

Of course, there are times when you do want to create a Web Forms page that updates data. This walkthrough illustrates one way to do that. It shows how you can use a DataGrid control to display data, allow users to edit it, and then send the changed data back to the source.

Note   The DataGrid control does not inherently include a facility for creating new records. The section "Next Steps" at the end of this topic includes suggestions for adding this ability.

When the page is running, it will look something like the following:

Aa728895.vbdatagidwithupdatesedit(en-us,VS.71).gif

In order to complete this walkthrough, you will need:

The Overall Process

The walkthrough is split into a number of smaller pieces:

  • Creating the Web Forms page.
  • Adding the necessary data components.
  • Adding the DataGrid control to display the data.
  • Adding code to read data from the database and bind the grid to the data.
  • Configuring the DataGrid control to allow users to edit data.
  • Adding the code to update the data.

Creating the Project and Form

The first step is to create a Web application and a Web Forms page.

To create the project and form

  1. On the File menu, point to New, then click Project.
  2. In the New Project dialog box, do the following:
    1. In the Project Types pane, choose either Visual Basic Projects or Visual C# Projects.
    2. In the Templates pane, choose ASP.NET Web Application.
    3. In the Location box, enter the complete URL for your application, including http://, the name of the server, and the name of your project. The Web server must have IIS version 5 or later and the .NET Framework installed on it. If you have IIS on your computer, you can specify http://localhost for the server. (If you normally use a proxy server to access the Internet, you might need to configure Internet Explorer to bypass the proxy server in order to use localhost.)

      When you click OK, a new Web Forms project is created at the root of the Web server you specified. In addition, a new Web Forms page called WebForm1.aspx is displayed in the Web Forms Designer in Design view.

      Tip   If you have trouble creating a Web application project, see Web Access Failed Dialog Box.

Creating and Configuring a Dataset

In Web Forms pages, you have several choices for how you can access data. One is to use a dataset, which is an in-memory data cache. Alternatively, you can access a database directly, using data commands to execute SQL statements or stored procedures. As a general rule, it is easier to update data if you use a dataset, and that is what you will use in this walkthrough. For more information, see Web Data Access Strategy Recommendations.

You do not directly add a dataset to a page. Instead, you will perform the following set of steps:

  1. Create a data adapter using a wizard. The adapter contains SQL statements used to read and write database information. The wizard helps you define the SQL statements you need. If necessary, the wizard also creates a connection to the database.
  2. Generate the dataset schema. In this process, you will have Visual Studio create a new dataset class based on the tables and columns you are accessing. When you generate the dataset class, you will also add an instance of it to the form.

It is important that you follow all the procedures in this section. Otherwise your page will not have the dataset that you will be using in subsequent parts of the walkthrough.

For an overview of data adapters, see Introduction to Data Adapters. For an overview of datasets, see Introduction to Datasets.

Configuring a Data Connection and Data Adapter

To begin, you create a data adapter that contains the SQL statement used to populate the dataset later. As part of this process, you define a connection to access a database. You configure the data adapter using a wizard, which makes it easy to create the SQL statements you need for data access.

Note   When the wizard is done, you must continue to the next section in order to generate a dataset and complete the data access portion of your page.

To create the data connection and data adapter

  1. Click WebForm1.aspx, and then from the Data tab of the Toolbox, drag a SqlDataAdapter object onto the page.
    Note   If you are not working with SQL Server, you use an adapter of type OleDbDataAdapter, which provides access to any OLE DB-compatible data source.

    The Data Adapter Configuration Wizard starts, which will help you create both the connection and the adapter.

  2. In the wizard, do the following:
    1. In the second pane, create or choose a connection pointing to the SQL Server Northwind database. For information about getting access to the database, see your database administrator.
      Note   You need appropriate read/write permissions on the SQL Server you are using. If SQL Server is on the same computer as IIS, it is recommended that you specify Windows integrated security when creating the connection. Otherwise, you can specify a user name and password and save that information with the connection, but doing so can compromise security. For more information, see Accessing SQL Server from a Web Application.
    2. In the third pane, specify that you want to use a SQL statement to access the database.
    3. In the fourth pane, create the following SQL statement:
      SELECT CategoryID, CategoryName, Description
      FROM Categories
      

      For assistance building the SQL statement, click Query Builder to launch the Query Builder dialog box.

      Note   In this walkthrough, you will populate the dataset with all the rows from the categories table. In production applications, you typically optimize data access by creating a query that returns only the columns and rows you need. For an example, see Walkthrough: Displaying Data in a Windows Form Using a Parameterized Query.
    4. Click Finish.

      The wizard creates a connection (SqlConnection1 or sqlConnection1) containing information about how to access your database. You will also have a data adapter (SqlDataAdapter1 or sqlDataAdapter1) that contains a query defining what table and columns in the database you want to access.

After the wizard is complete, you need to generate the dataset based on the SQL query that you created during this procedure. For details, see the next section.

Creating the Dataset

After you have established the means to connect to the database and specified the information you want (via the SQL command in the data adapter), you can have Visual Studio create a dataset. Visual Studio can generate the dataset automatically based on the query you specified for the data adapter. The dataset is an instance of the DataSet class based on a corresponding schema (.xsd file) that describes the class's elements (table, columns, and constraints). For details about the relationship between datasets and schemas, see Introduction to Data Access with ADO.NET.

To generate a dataset

  1. From the Data menu, choose Generate DataSet.
    Tip   If the Generate DataSet command is not enabled, click the page; the page must have focus for the command to appear.

    The Generate Dataset dialog box appears.

  2. Select the New option and name the dataset dsCategories.

    In the list under Choose which table(s) to add to the dataset, make sure the Categories table is selected.

  3. Make sure Add this dataset to the designer is checked, and then click OK.

    Visual Studio generates a typed dataset class (dsCategories) and a schema that defines the dataset. You will see the new schema (dsCategories.xsd) in Solution Explorer.

    Tip   In Solution Explorer, click the Show All Files toolbar button to see the schema file's dependent .vb or .cs file, which contains the code that defines your new dataset class.

    Finally, Visual Studio adds an instance of the new dataset class (dsCategories1) to the page.

At this point you have set up everything you need in order to get information out of database and into a dataset.

Adding a DataGrid Control to Display the Data

In this walkthrough, you will add a single control — a DataGrid control — that can display all the records from the dataset at the same time and allows you to add the ability to edit records.

The data grid must be bound to the dataset in order to display the data.

To add a bound DataGrid control to the form

  1. If you have not already done so, switch to the Web Forms Designer by clicking the tab at the top of the current window.
  2. From the Web Forms tab of the Toolbox, drag a DataGrid control onto the form.
  3. Select the control, press F4 to display the Properties window, and at the bottom of the window, click Property Builder.

    The DataGrid1 Properties dialog box appears.

  4. In the General tab, make the following settings:
    PropertySettingDescription
    DataSourcedsCategories1Binds the grid to the dataset.
    DataMemberCategoriesSpecifies that the grid should display data from the categories table in the dataset
    Data key fieldCategoryIDSpecifies that the primary key for categories record is the CategoryID column. This will allow you later to identify which record to update in the dataset.
  5. Click OK to close the DataGrid1 Properties dialog box.
  6. If you want to change the appearance of the grid, set the Font, BackColor, and other properties.
    Tip   An easy way to set the grid's appearance is to click Auto Format at the bottom of the Properties window and select a predefined look.

Filling the Dataset and Displaying Data in the DataGrid Control

Although the grid is bound to the dataset you created, the dataset itself is not automatically filled in. Instead, you must fill the dataset yourself by calling a data-adapter method. For details about filling datasets, see Introduction to Datasets.

Even after the dataset is filled in, the DataGrid control does not automatically display the data. You must explicitly bind the grid to its data source. For more information, see Introduction to Data Binding in Web Forms Pages.

To fill the dataset and display data in the DataGrid control

  1. Double-click the page to display the page's class file in the Code Editor.
  2. In the Page_Load event handler, call the data adapter's Fill method, passing it the dataset you want to populate:
    ' Visual Basic
    SqlDataAdapter1.Fill(DsCategories1)
    
    //C#
    sqlDataAdapter1.Fill(dsCategories1);
    
  3. Call the DataGrid control's DataBind method to bind the control to the dataset. You do not want to rebind the control each time the page makes a round trip, however, because if you do, you will lose changes that the user has made in the grid. You should therefore bind the grid only at these times:
    • The first time the page is called.
    • When the dataset has changed.

    For now, you want to bind the grid the first time the page is called, which you can do by testing the page's IsPostBack property. Add code to the Page_Load event handler after the call to the adapter's Fill method. The complete handler will look like the following:

    ' Visual Basic
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       'Put user code to initialize the page here
       SqlDataAdapter1.Fill(DsCategories1)
       If Not IsPostBack Then
          DataGrid1.DataBind()
       End If
    End Sub
    
    // C#
    private void Page_Load(object sender, System.EventArgs e)
    {
       // Put user code to initialize the page here
       sqlDataAdapter1.Fill(dsCategories1);
       if (!IsPostBack)
       {
          DataGrid1.DataBind();
       }
    }
    

Adding the Ability to Edit Data

As configured, the DataGrid control will display information from the Categories table. But you also want users to be able to edit individual rows in the grid. To do this, you add an Edit button to each row of the grid. The user clicks the button and the grid is redisplayed in edit mode, with text boxes where users can edit the individual columns. When the row is in edit mode, the Edit button is replaced with two other buttons, an Update button and a Cancel button, as shown in the following figure:

Aa728895.vbdatagridwithupdatesupdate(en-us,VS.71).gif

You can set properties of the DataGrid control to display these buttons. However, the buttons are not hooked up automatically; instead, when an Edit or Cancel or Update button is clicked, it raises an event that you respond to. You will need to add short event handlers that do the following:

  • Edit button – set the current row into edit mode.
  • Cancel button – return the row to display mode.

The event handler for the Update button is more involved, since it performs the update that is the heart of this walkthrough. You will read about this in the next section.

To add editing capability to the DataGrid control

  1. In Design view of the Web Forms Designer, select the DataGrid control, press F4 to display the Properties window, and then click Property Builder at the bottom of the window.

    The DataGrid1 Properties dialog box is displayed.

  2. Click the Columns tab.
  3. Under Column list, scroll down in the Available columns list and open the Button Column node.
  4. Select Edit, Update, Cancel and click the add ( Aa728895.vxaddbutton(en-us,VS.71).gif )button to add the buttons to the Selected columns box.
  5. Click OK.

    The DataGrid control is redisplayed with an Edit link button in the left-hand column. (You do not initially see the Update and Cancel buttons.)

Now that you have the Edit button, you need to create the event handlers to set edit mode for the rows. To control edit mode, you set the DataGrid control's EditItemIndex property to the index (zero-based) of the row to edit. For example, to put the third row into edit mode, you set the property to 2. To return a row to display mode, you set the property to –1. After changing edit mode, you must rebind the grid so it displays the data in the row.

You can determine what row the user is in from the event-object passed to the handler. The event object for these events contains an Item property that represents the entire DataGrid row being updated. The Item object in turn supports various properties, including the Item.ItemIndex property, which returns the index value of the row you are working with.

To set edit modes

  1. (In Visual Basic) Right-click the page and choose View Code to open the page's class file in the Code Editor.

    -or-

    (In Visual C#) In Design view, select the grid and then press F4 to open the Properties window.

  2. (In Visual Basic) In the left-hand drop-down list at the top of the Code Editor, select DataGrid1.

    -or-

    (In Visual C#) Click the Events button (Aa728895.vxeventsbutton_propertieswindow(en-us,VS.71).gif) at the top of the Properties window.

  3. (In Visual Basic) In the right-hand drop-down list at the top of the Code Editor, select EditCommand.

    -or-

    (In Visual C#) Double-click EditCommand in the Properties window.

    A DataGrid1_EditCommand handler is created.

  4. Repeat Steps 2 and 3 for the CancelCommand event.

    A DataGrid1_CancelCommand handler is created.

  5. In the EditCommand event handler, add the following code:
    ' Visual Basic
    DataGrid1.EditItemIndex = e.Item.ItemIndex
    DataGrid1.DataBind()
    
    // C#
    DataGrid1.EditItemIndex = e.Item.ItemIndex;
    DataGrid1.DataBind();
    
  6. In the CancelCommand event handler, add the following code:
    ' Visual Basic
    DataGrid1.EditItemIndex = -1
    DataGrid1.DataBind()
    
    // C#
    DataGrid1.EditItemIndex = -1;
    DataGrid1.DataBind();
    

Testing What You Have So Far

You now have a DataGrid control that displays data from a dataset (after the dataset is filled from the database) and you have configured the grid with an Edit button for each row. Even though the page is not yet complete, it is useful to test it now to make sure that the edit capability is working correctly.

To test what you have so far

  1. In Solution Explorer, right-click your Web Forms page and choose View in Browser.

    The project is compiled and the Web Forms page appears in a browser pane in the designer. If everything is working correctly, the grid will be filled with data and the first column in the grid will contain links that read "Edit."

  2. Click the Edit link for any row in the grid.

    The row is redisplayed with these changes:

    • The Edit link is replaced with Update and Cancel links.
    • The data is redisplayed in TextBox controls.
  3. Click Cancel.

    The row is redisplayed in its original form.

The next section details how you can have the Update link write changes from the grid to the dataset and database.

Updating the Dataset and Database

Up to this point, the DataGrid control has done most of the work involved in simply displaying data. However, as with other ASP.NET server controls, the grid does not include automatic provisions for updates — that is, for taking changes made by a user in the grid and sending them back to the data source. To perform updates, you will need to write some code.

The update will actually occur in two stages. First, you must update the dataset with changes made in the grid. Then you must write changes from the dataset back to the database. For more information, see Introduction to Dataset Updates.

When a grid row is in edit mode, the leftmost column contains an Update link. When users click the link, it raises an UpdateCommand event. You will write all your update code in the handler for this event.

To create the UpdateCommand handler

  1. (In Visual Basic) If it is not already open, open the Code Editor again.

    -or-

    (In Visual C#) In Design view, select the grid and then press F4 to open the Properties window.

  2. (In Visual Basic) In the left-hand drop-down list at the top of the Code Editor, select DataGrid1.

    -or-

    (In Visual C#) Click the Events button (Aa728895.vxeventsbutton_propertieswindow(en-us,VS.71).gif) at the top of the Properties window.

  3. (In Visual Basic) In the right-hand drop-down list at the top of the Code Editor, select UpdateCommand.

    -or-

    (In Visual C#) Double-click UpdateCommand in the grid.

    A DataGrid1_UpdateCommand event handler is created.

Steps for Updating From the DataGrid Control

The outline for what you will be doing is this:

  1. Determine what row (by index) in the DataGrid control was updated. Then get the datakey out of that grid row so that you identify what row (by ID) is being updated.
  2. Get the changed values out of the grid row that the user updated.
  3. Use the datakey value to find the corresponding row in the dataset table and then write the changes to that row. At this point, you have updated the dataset, but not yet the database itself.
  4. Send changes from the dataset to the database. This executes a SQL command or stored procedure that copies changes from the dataset to the database.
  5. Refresh the contents of the DataGrid control.
  6. The following sections explain the details of each of these steps. If you prefer, you can skip these explanations and go directly to the code that follows.

To update from the DataGrid control

  1. Identify what DataGrid row was updated by getting the ItemIndex property of the row (Item object) passed in the event object. Then use the index value to get the corresponding value out of the grid's DataKeys collection:
    ' Visual Basic
    Dim key As String = DataGrid1.DataKeys(e.Item.ItemIndex).ToString()
    
    // C#
    string key = DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
    
  2. Get the changed values out of the DataGrid row. To do so:
    1. From the item passed in the event object, get the appropriate cell (zero-based) out of the Cells collection from the item passed in the event object. For example, the left-most column in the grid is Cells(0).
    2. For each cell, get its Controls collection, which contains all the elements that appear in the cell.
    3. Get the first (and only) control out of the collection — in this case, a TextBox control. To get the TextBox, declare a local variable of type TextBox and cast the object in the Controls collection to it.
    4. Get the TextBox control's value (its Text property).

      The following example shows how to perform these steps.

      ' Visual Basic
      Dim categoryName, categoryDescription As String
      Dim tb As TextBox
      tb = CType(e.Item.Cells(2).Controls(0), TextBox)
      categoryName = tb.Text
      tb = CType(e.Item.Cells(3).Controls(0), TextBox)
      categoryDescription = tb.Text
      
      // C#
      string categoryName;
      string categoryDescription;
      TextBox tb;
      tb = (TextBox) e.Item.Cells[2].Controls[0];
      categoryName = tb.Text;
      tb = (TextBox) e.Item.Cells[3].Controls[0];
      categoryDescription = tb.Text
      
  3. Find the corresponding row in the data table. The typed dsCategories dataset contains a special FindBy method — in this case, the FindByCategoryID method — that locates a row by its primary key and returns a reference to it. Create a variable for the typed data row and call the method:
    ' Visual Basic
    Dim r As dsCategories.CategoriesRow
    r = DsCategories1.Categories.FindByCategoryID(key)
    
    // C#
    dsCategories.CategoriesRow r;
    r = dsCategories1.Categories.FindByCategoryID(int.Parse(key));
    
  4. Update the row by changing values in the row you located in Step 3, as in the following example:
    ' Visual Basic
    r.CategoryName = categoryName
    r.Description = categoryDescription
    
    // C#
    r.CategoryName = categoryName;
    r.Description = categoryDescription;
    
  5. Send changes from the dataset to the database by calling the data adapter's Update method:
    ' Visual Basic
    SqlDataAdapter1.Update(DsCategories1)
    
    DataGrid1.DataBind()
    
    // C#
    sqlDataAdapter1.Update(dsCategories1);
    DataGrid1.DataBind();
    
  6. Switch the current row in the grid out of editing mode.
    ' Visual Basic
    DataGrid1.EditItemIndex = -1
    
    // C#
    DataGrid1.EditItemIndex = -1;
    
  7. Data-bind the DataGrid control:
    ' Visual Basic
    DataGrid1.DataBind()
    
    // C#
    DataGrid1.DataBind();
    

The following code shows what the completed UpdateCommand event handler looks like. Copy this code and paste it into the class file for the Web Forms page.

Tip   Be sure to overwrite the skeleton event handler you created earlier, otherwise you will have two methods with identical names and signatures.
' Visual Basic
Private Sub DataGrid1_UpdateCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.UpdateCommand
    Dim categoryName, categoryDescription As String

    ' Gets the value of the key field of the row being updated
    Dim key As String = DataGrid1.DataKeys(e.Item.ItemIndex).ToString()

    ' Gets get the value of the controls (textboxes) that the user
    ' updated. The DataGrid columns are exposed as the Cells collection.
    ' Each cell has a collection of controls. In this case, there is only one 
    ' control in each cell -- a TextBox control. To get its value,
    ' you copy the TextBox to a local instance (which requires casting)
    ' and extract its Text property.
    '
    ' The first column -- Cells(0) -- contains the Update and Cancel buttons.
    Dim tb As TextBox

    ' Gets the value the TextBox control in the third column
    tb = CType(e.Item.Cells(2).Controls(0), TextBox)
    categoryName = tb.Text

    ' Gets the value the TextBox control in the fourth column
    tb = CType(e.Item.Cells(3).Controls(0), TextBox)
    categoryDescription = tb.Text

    ' Finds the row in the dataset table that matches the 
    ' one the user updated in the grid. This example uses a 
    ' special Find method defined for the typed dataset, which
    ' returns a reference to the row.
    Dim r As dsCategories.CategoriesRow
    r = DsCategories1.Categories.FindByCategoryID(key)

    ' Updates the dataset table.
    r.CategoryName = categoryName
    r.Description = categoryDescription

    ' Calls a SQL statement to update the database from the dataset
    SqlDataAdapter1.Update(DsCategories1)

    ' Takes the DataGrid row out of editing mode
    DataGrid1.EditItemIndex = -1

    ' Refreshes the grid
    DataGrid1.DataBind()
End Sub

// C#
private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{   
   string categoryName, categoryDescription;

   // Gets the value of the key field of the row being updated
   string key = DataGrid1.DataKeys[e.Item.ItemIndex].ToString();

   // Gets get the value of the controls (textboxes) that the user
   // updated. The DataGrid columns are exposed as the Cells collection.
   // Each cell has a collection of controls. In this case, there is only    one 
   // control in each cell -- a TextBox control. To get its value,
   // you copy the TextBox to a local instance (which requires casting)
   // and extract its Text property.
   //
   // The first column -- Cells(0) -- contains the Update and Cancel buttons.
   TextBox tb;

   // Gets the value the TextBox control in the third column
   tb = (TextBox)(e.Item.Cells[2].Controls[0]);
   categoryName = tb.Text;

   // Gets the value the TextBox control in the fourth column
   tb = (TextBox)(e.Item.Cells[3].Controls[0]);
   categoryDescription = tb.Text;

   // Finds the row in the dataset table that matches the 
   // one the user updated in the grid. This example uses a 
   // special Find method defined for the typed dataset, which
   // returns a reference to the row.
   dsCategories.CategoriesRow r;
   r = dsCategories1.Categories.FindByCategoryID(int.Parse(key));

   // Updates the dataset table.
   r.CategoryName = categoryName;
   r.Description = categoryDescription;

   // Calls a SQL statement to update the database from the dataset
   sqlDataAdapter1.Update(dsCategories1);

   // Takes the DataGrid row out of editing mode
   DataGrid1.EditItemIndex = -1;

   // Refreshes the grid
   DataGrid1.DataBind();
}

Testing

You are now finished. To illustrate how the grid works and make sure it is updating data properly, you should test the page.

To test the page

  1. In Solution Explorer, right-click your Web Forms page and choose View in Browser.

    The project is compiled and the Web Forms page appears in a browser pane in the designer.

  2. Click the Edit link for any row in the grid, and edit the row using the text boxes.
  3. Click Update.

    The grid is redisplayed with your changes. If you examine the database, you will see that the change has been written there are well.

Next Steps

In this walkthrough, you used a DataGrid control on a Web Forms page not just to view data, but also to edit it. For the sake of clarity, the walkthrough skipped some details that you would likely want to think about in a production application. Some of the areas in which you might want to enhance what you have learned in this walkthrough are:

Enhancing the DataGrid Control

This walkthrough did not take advantage of some of the DataGrid control's more advanced features. Some of the enhancements you could make are:

Caching the Dataset

In the walkthrough, the dataset is reinstantiated and refilled from the database each time the page makes a round trip to the server. This strategy, while straightforward to implement, can result in unnecessary traffic to your database server.

An alternative is to store the dataset after it is filled and each time it is changed. Then, instead of rereading the database information, you can restore the dataset with each round trip. There are a variety of options for storing the dataset, including in session state (on the server) or in view state (on the client, in the page). For details about what strategy to use, see State Management Recommendations.

For example, if you want to store the dataset in session state, you might include code such as the following in the Page_Load event handler:

' Visual Basic
If Session("mydatset") Is Nothing Then
   SqlDataAdapter1.Fill(DsCategories1)
   Session("mydataset") = DsCategories1
Else
   DsCategories1 = CType(Session("mydatset"), dsCategories)
End If
If Not Page.IsPostBack Then
   DataGrid1.DataBind()
End If

// C#
if (Session["mydatset"] == null)
{
   sqlDataAdapter1.Fill(dsCategories1);
   Session["mydataset"] = dsCategories1;
}
else
{
   dsCategories1 = (dsCategories)Session["mydatset"];
}
if (! Page.IsPostBack) 
   {
        DataGrid1.DataBind();
   }

Note that if you store a dataset in Session or Application state, you need to cast it to the appropriate dataset type when you get it back out.

Be sure to refresh the copy of the dataset in session state each time it changes. For example, you might add the following line in the UpdateCommand event handler immediately after you update the database:

' Visual Basic
SqlDataAdapter1.Update(DsCategories1)
Session("mydataset") = DsCategories1

// C#
sqlDataAdapter1.Update(dsCategories1);
Session["mydataset"] = dsCategories1;

Using Direct Access to the Database instead of a Dataset

In the walkthrough, you created a dataset and bound the grid to it. To update the database, you first updated the dataset, then used the data adapter's Update method to send changes to the database.

Using a dataset makes it easy to perform updates, but at the cost of some memory and a very slight performance overhead. As an alternative, you can use data commands (OleDbCommand Class or SqlCommand Class objects) to execute SQL statements or stored procedures directly. For example, you can configure a data command with a parameterized SQL Update statement to update the Categories table in the database. After getting the changes from the grid, you set parameters for the Update statement and then execute it.

For more information, see Introduction to DataCommand Objects in Visual Studio.

Validating Data

In a production application, you would probably include validation checks to be sure that the changes entered by a user were valid. For details, see Data Validation in Datasets.

Concurrency Control

In the walkthrough, you sent updates to the database without worrying about whether the record you were updating had been changed by another user. However, in production applications, you will usually want to include error checking to be sure that you maintain the integrity of your database. For details, see Concurrency Control in ADO.NET.

Adding Records Using the DataGrid Control

Although the DataGrid control allows you to display and edit data, it does not directly include the ability to add new records to a dataset or to a database table. You can add this ability indirectly by using a strategy such as the following:

  • Add a new, blank record to the data source.
  • Rebind the grid; this will display the new, blank record.
  • Put the new grid row into edit mode, and when the user saves changes, update the new record with the user's information, as you would any existing record.

The exact steps you follow depend on the type of data source you are using (for example, whether it is a dataset or the database itself). You might also encounter limitations imposed on new records by primary key or foreign key constraints.

An example of adding a new record using the DataGrid control is illustrated in Top Questions about the DataGrid Web Server Control.

Security

When you create Web Forms, you should understand the types of security issues that can arise. For details, see Overview of Web Application Security Threats.

See Also

Walkthrough: Displaying Data in a Web Forms Page | Walkthrough: Creating Read-Only Data Access in a Web Forms Page | Walkthrough: Creating a Distributed Application | Walkthrough: Updating Data using a Database Update Query in Web Forms | Walkthrough: Validating User Input in a Web Forms Page

Show:
© 2014 Microsoft