Compartir a través de


Modifying Data Using a FormView Web Server Control

The FormView control provides templates to allow users to edit records without requiring programming. You can specify a template in the FormView control for different rendering modes. You can specify an ItemTemplate template for read-only mode, an InsertItemTemplate template for insert mode, and an EditItemTemplate template for edit mode. For more information about FormView templates, see Creating Templates for the FormView Web Server Control.

How the FormView Control Modifies Bound Data

The FormView control displays the specified templates to provide a user interface (UI) that allows users to modify the contents of a record. Each template contains the command buttons that a user can click to perform an edit or insert action. When the user clicks a command button, the FormView control redisplays the bound record with the specified edit or insert template to allow users to modify the record.

An insert or edit template typically includes an "Insert" button to allow users to display a blank record or an "Update" button to save a change. When users click the insert or update button, the FormView control passes the bound values and primary key information to the associated data source control, which performs the appropriate update. For example, the SqlDataSource control executes a SQL Update statement using the changed data as parameter values. The ObjectDataSource control calls its update method, passing the changes as part of the method call.

When the FormView control is performing an insert operation, it passes the values to be inserted in the data source using the Values dictionary collection.

The FormView control passes values to the data source for an update or delete operation in three dictionary collections: the Keys dictionary, the NewValues dictionary, and the OldValues dictionary. You can access each dictionary using the arguments passed to the FormView control's insert, update or delete events.

The Keys dictionary contains the names and values of fields that uniquely identify the record to update or delete, and always contains the original values of the key fields. To specify which fields are placed in the Keys dictionary, set the DataKeyNames property to a comma-separated list of field names that represent the primary key of your data. An array is automatically populated with the values associated with the fields specified for the DataKeyNames property.

Note

The original primary key values for the fields specified in the DataKeyNames property are stored in view state. If your primary key values contain sensitive information, you should encrypt the view state contents by setting the page's ViewStateEncryptionMode property to Always.

The Values and NewValues dictionaries contain the current values from the controls in the record being inserted or edited in the FormView control. The OldValues dictionary contains any original values of fields except the key fields, which are included in the Keys dictionary. New values for editable key fields are contained in the NewValues dictionary.

The data source control uses the values from the Keys, Values, NewValues, and OldValues dictionaries as parameters for the insert, update, or delete command. For information about how data source control parameters are created based on the dictionaries created for bound values, see How a Data Source Control Creates Parameters for Data-bound Fields.

After the update is complete, the FormView control raises its ItemUpdated event. This event allows you to perform post-query logic such as integrity checks. Similarly, the FormView control raises its ItemInserted event after an insert, and its ItemDeleted event after a delete.

After the update is complete and all events have been raised, the FormView control rebinds to the data source control.

Example

The following code example uses a GridView control and a FormView control to display data. The FormView control is configured to allow the data to be modified.

Security noteSecurity Note:

This code example contains a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  Sub EmployeesGridView_OnSelectedIndexChanged(sender As Object, e As EventArgs)
    EmployeeDetailsSqlDataSource.SelectParameters("EmpID").DefaultValue = _
      EmployeesGridView.SelectedValue.ToString()
    EmployeeFormView.DataBind()
  End Sub

  Sub EmployeeFormView_ItemUpdated(sender As Object, e As FormViewUpdatedEventArgs)
    EmployeesGridView.DataBind()
  End Sub

  Sub EmployeeFormView_ItemDeleted(sender As Object, e As FormViewDeletedEventArgs)
    EmployeesGridView.DataBind()
  End Sub

  Sub EmployeeDetailsSqlDataSource_OnInserted(sender As Object, e As SqlDataSourceStatusEventArgs)
    Dim command As System.Data.Common.DbCommand = e.Command    

    EmployeeDetailsSqlDataSource.SelectParameters("EmpID").DefaultValue = _
      command.Parameters("@EmpID").Value.ToString()

    EmployeesGridView.DataBind()
    EmployeeFormView.DataBind()
  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>FormView Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <h3>FormView Example</h3>

        <table cellspacing="10">

          <tr>
            <td>
              <asp:GridView ID="EmployeesGridView" 
                DataSourceID="EmployeesSqlDataSource" 
                AutoGenerateColumns="false"
                DataKeyNames="EmployeeID" 
                OnSelectedIndexChanged="EmployeesGridView_OnSelectedIndexChanged"
                RunAt="Server">

                <HeaderStyle backcolor="Navy"
                  forecolor="White" />

                <Columns>

                  <asp:ButtonField Text="Details..."
                    HeaderText="Show<BR>Details"
                    CommandName="Select"/>  

                  <asp:BoundField DataField="EmployeeID" HeaderText="Employee ID"/>
                  <asp:BoundField DataField="LastName"   HeaderText="Last Name"/>                        
                  <asp:BoundField DataField="FirstName"  HeaderText="First Name"/>

                </Columns>

              </asp:GridView>

            </td>

            <td valign="top">

              <asp:FormView ID="EmployeeFormView"
                DataSourceID="EmployeeDetailsSqlDataSource"
                DataKeyNames="EmployeeID"     
                Gridlines="Both" 
                OnItemUpdated="EmployeeFormView_ItemUpdated"
                OnItemDeleted="EmployeeFormView_ItemDeleted"      
                RunAt="server">

                <HeaderStyle backcolor="Navy"
                  forecolor="White"/>

                <RowStyle backcolor="White"/>         

                <EditRowStyle backcolor="LightCyan"/>

                <ItemTemplate>
                  <table>
                    <tr><td align="right"><b>Employee ID:</b></td><td><%# Eval("EmployeeID") %></td></tr>
                    <tr><td align="right"><b>First Name:</b></td> <td><%# Eval("FirstName") %></td></tr>
                    <tr><td align="right"><b>Last Name:</b></td>  <td><%# Eval("LastName") %></td></tr>
                    <tr>
                      <td colspan="2">
                        <asp:LinkButton ID="EditButton"
                                        Text="Edit"
                                        CommandName="Edit"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="NewButton"
                                        Text="New"
                                        CommandName="New"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="DeleteButton"
                                        Text="Delete"
                                        CommandName="Delete"
                                        RunAt="server"/>
                      </td>
                    </tr>
                  </table>                 

                </ItemTemplate>

                <EditItemTemplate>


                  <table>
                    <tr><td align="right"><b>Employee ID:</b></td><td><%# Eval("EmployeeID") %></td></tr>
                    <tr><td align="right"><b>First Name:</b></td>
                        <td><asp:TextBox ID="EditFirstNameTextBox" 
                                         Text='<%# Bind("FirstName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr><td align="right"><b>Last Name:</b></td>
                        <td><asp:TextBox ID="EditLastNameTextBox" 
                                         Text='<%# Bind("LastName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr>
                      <td colspan="2">
                        <asp:LinkButton ID="UpdateButton"
                                        Text="Update"
                                        CommandName="Update"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="CancelUpdateButton"
                                        Text="Cancel"
                                        CommandName="Cancel"
                                        RunAt="server"/>
                      </td>
                    </tr>
                  </table>                 

                </EditItemTemplate>

                <InsertItemTemplate>


                  <table>
                    <tr><td align="right"><b>First Name:</b></td>
                        <td><asp:TextBox ID="InsertFirstNameTextBox" 
                                         Text='<%# Bind("FirstName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr><td align="right"><b>Last Name:</b></td>
                        <td><asp:TextBox ID="InsertLastNameTextBox" 
                                         Text='<%# Bind("LastName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr>
                      <td colspan="2">
                        <asp:LinkButton ID="InsertButton"
                                        Text="Insert"
                                        CommandName="Insert"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="CancelInsertButton"
                                        Text="Cancel"
                                        CommandName="Cancel"
                                        RunAt="server"/>
                      </td>
                    </tr>
                  </table>                 

                </InsertItemTemplate>

              </asp:FormView>

            </td>

          </tr>

        </table>


        <asp:sqlDataSource ID="EmployeesSqlDataSource"  
          selectCommand="SELECT EmployeeID, FirstName, LastName FROM Employees" 
          connectionstring="<%$ ConnectionStrings:NorthwindConnection %>" 
          RunAt="server">
        </asp:sqlDataSource>

        <asp:sqlDataSource ID="EmployeeDetailsSqlDataSource" 
          SelectCommand="SELECT EmployeeID, LastName, FirstName FROM Employees WHERE EmployeeID = @EmpID"

          InsertCommand="INSERT INTO Employees(LastName, FirstName) VALUES (@LastName, @FirstName); 
                         SELECT @EmpID = SCOPE_IDENTITY()"
          UpdateCommand="UPDATE Employees SET LastName=@LastName, FirstName=@FirstName 
                           WHERE EmployeeID=@EmployeeID"
          DeleteCommand="DELETE Employees WHERE EmployeeID=@EmployeeID"

          ConnectionString="<%$ ConnectionStrings:NorthwindConnection %>"
          OnInserted="EmployeeDetailsSqlDataSource_OnInserted"
          RunAt="server">

          <SelectParameters>
            <asp:Parameter Name="EmpID" Type="Int32" DefaultValue="0" />
          </SelectParameters>

          <InsertParameters>
            <asp:Parameter Name="EmpID" Direction="Output" Type="Int32" DefaultValue="0" />
          </InsertParameters>

        </asp:sqlDataSource>

      </form>
  </body>
</html>

<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  void EmployeesGridView_OnSelectedIndexChanged(Object sender, EventArgs e)
  {
    EmployeeDetailsSqlDataSource.SelectParameters["EmpID"].DefaultValue = 
      EmployeesGridView.SelectedValue.ToString();
    EmployeeFormView.DataBind();
  }

  void EmployeeFormView_ItemUpdated(Object sender, FormViewUpdatedEventArgs e)
  {
    EmployeesGridView.DataBind();
  }

  void EmployeeFormView_ItemDeleted(Object sender, FormViewDeletedEventArgs e)
  {
    EmployeesGridView.DataBind();
  }

  void EmployeeDetailsSqlDataSource_OnInserted(Object sender, SqlDataSourceStatusEventArgs e)
  {
    System.Data.Common.DbCommand command = e.Command;    

    EmployeeDetailsSqlDataSource.SelectParameters["EmpID"].DefaultValue = 
      command.Parameters["@EmpID"].Value.ToString();

    EmployeesGridView.DataBind();
    EmployeeFormView.DataBind();
  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>FormView Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <h3>FormView Example</h3>

        <table cellspacing="10">

          <tr>
            <td>
              <asp:GridView ID="EmployeesGridView" 
                DataSourceID="EmployeesSqlDataSource" 
                AutoGenerateColumns="false"
                DataKeyNames="EmployeeID" 
                OnSelectedIndexChanged="EmployeesGridView_OnSelectedIndexChanged"
                RunAt="Server">

                <HeaderStyle backcolor="Navy"
                  forecolor="White" />

                <Columns>

                  <asp:ButtonField Text="Details..."
                    HeaderText="Show<BR>Details"
                    CommandName="Select"/>  

                  <asp:BoundField DataField="EmployeeID" HeaderText="Employee ID"/>
                  <asp:BoundField DataField="LastName"   HeaderText="Last Name"/>                        
                  <asp:BoundField DataField="FirstName"  HeaderText="First Name"/>

                </Columns>

              </asp:GridView>

            </td>

            <td valign="top">

              <asp:FormView ID="EmployeeFormView"
                DataSourceID="EmployeeDetailsSqlDataSource"
                DataKeyNames="EmployeeID"     
                Gridlines="Both" 
                OnItemUpdated="EmployeeFormView_ItemUpdated"
                OnItemDeleted="EmployeeFormView_ItemDeleted"      
                RunAt="server">

                <HeaderStyle backcolor="Navy"
                  forecolor="White"/>

                <RowStyle backcolor="White"/>         

                <EditRowStyle backcolor="LightCyan"/>

                <ItemTemplate>
                  <table>
                    <tr><td align="right"><b>Employee ID:</b></td><td><%# Eval("EmployeeID") %></td></tr>
                    <tr><td align="right"><b>First Name:</b></td> <td><%# Eval("FirstName") %></td></tr>
                    <tr><td align="right"><b>Last Name:</b></td>  <td><%# Eval("LastName") %></td></tr>
                    <tr>
                      <td colspan="2">
                        <asp:LinkButton ID="EditButton"
                                        Text="Edit"
                                        CommandName="Edit"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="NewButton"
                                        Text="New"
                                        CommandName="New"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="DeleteButton"
                                        Text="Delete"
                                        CommandName="Delete"
                                        RunAt="server"/>
                      </td>
                    </tr>
                  </table>                 

                </ItemTemplate>

                <EditItemTemplate>


                  <table>
                    <tr><td align="right"><b>Employee ID:</b></td><td><%# Eval("EmployeeID") %></td></tr>
                    <tr><td align="right"><b>First Name:</b></td>
                        <td><asp:TextBox ID="EditFirstNameTextBox" 
                                         Text='<%# Bind("FirstName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr><td align="right"><b>Last Name:</b></td>
                        <td><asp:TextBox ID="EditLastNameTextBox" 
                                         Text='<%# Bind("LastName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr>
                      <td colspan="2">
                        <asp:LinkButton ID="UpdateButton"
                                        Text="Update"
                                        CommandName="Update"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="CancelUpdateButton"
                                        Text="Cancel"
                                        CommandName="Cancel"
                                        RunAt="server"/>
                      </td>
                    </tr>
                  </table>                 

                </EditItemTemplate>

                <InsertItemTemplate>


                  <table>
                    <tr><td align="right"><b>First Name:</b></td>
                        <td><asp:TextBox ID="InsertFirstNameTextBox" 
                                         Text='<%# Bind("FirstName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr><td align="right"><b>Last Name:</b></td>
                        <td><asp:TextBox ID="InsertLastNameTextBox" 
                                         Text='<%# Bind("LastName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr>
                      <td colspan="2">
                        <asp:LinkButton ID="InsertButton"
                                        Text="Insert"
                                        CommandName="Insert"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="CancelInsertButton"
                                        Text="Cancel"
                                        CommandName="Cancel"
                                        RunAt="server"/>
                      </td>
                    </tr>
                  </table>                 

                </InsertItemTemplate>

              </asp:FormView>

            </td>

          </tr>

        </table>


        <asp:sqlDataSource ID="EmployeesSqlDataSource"  
          selectCommand="SELECT EmployeeID, FirstName, LastName FROM Employees" 
          connectionstring="<%$ ConnectionStrings:NorthwindConnection %>" 
          RunAt="server">
        </asp:sqlDataSource>

        <asp:sqlDataSource ID="EmployeeDetailsSqlDataSource" 
          SelectCommand="SELECT EmployeeID, LastName, FirstName FROM Employees WHERE EmployeeID = @EmpID"

          InsertCommand="INSERT INTO Employees(LastName, FirstName) VALUES (@LastName, @FirstName); 
                         SELECT @EmpID = SCOPE_IDENTITY()"
          UpdateCommand="UPDATE Employees SET LastName=@LastName, FirstName=@FirstName 
                           WHERE EmployeeID=@EmployeeID"
          DeleteCommand="DELETE Employees WHERE EmployeeID=@EmployeeID"

          ConnectionString="<%$ ConnectionStrings:NorthwindConnection %>"
          OnInserted="EmployeeDetailsSqlDataSource_OnInserted"
          RunAt="server">

          <SelectParameters>
            <asp:Parameter Name="EmpID" Type="Int32" DefaultValue="0" />
          </SelectParameters>

          <InsertParameters>
            <asp:Parameter Name="EmpID" Direction="Output" Type="Int32" DefaultValue="0" />
          </InsertParameters>

        </asp:sqlDataSource>

      </form>
  </body>
</html>

See Also

Concepts

FormView Web Server Control Overview

Data Source Controls Overview