Modificando Dados Usando Controles de Fonte de Dados

Data source controls greatly expand the capabilities of data-bound controls such as the ListView, GridView, FormView, and DetailsView controls to modify data at the data source without requiring extensive additional code.O controle de fonte de dados executa a modificação de dados, então controles vinculados de dados podem oferecer suporte de atualizações sem informações específicas sobre o banco de dados ou outra fonte de dados.Você pode usar controles de fonte de dados diferentes com qualquer combinação de controles na página.In addition, you can change the database or data source that a data-bound control works with by changing its DataSourceID to point to a different data source control.

Comandos de Modificação de Dados

You can configure the ObjectDataSource, SqlDataSource, and AccessDataSource controls with data commands to insert, update, and delete data in their associated data store.

When you use the LinqDataSource control for data modification, you do not have to provide commands to insert, update, and delete data.Those commands are automatically generated for you.

Modifying Data with the LinqDataSource Control

You enable insert, update, and delete operations with the LinqDataSource control by setting the EnableInsert, EnableUpdate, and EnableDelete properties to true.When these properties are true, the LinqDataSource control uses LINQ to SQL to automatically create the commands to modify the data.

The following example shows a LinqDataSource control that has EnableInsert, EnableUpdate and EnableDelete set to true.A DetailsView control displays the data and creates a button for each command that lets users modify the data.

<asp:LinqDataSource 
    ContextTypeName="ExampleDataContext" 
    TableName="Products" 
    EnableUpdate="true"
    EnableInsert="true"
    EnableDelete="true"
    ID="LinqDataSource1" 
    >
</asp:LinqDataSource>
<asp:DetailsView 
    DataKeyNames="ProductID"
    AutoGenerateEditButton="true"
    AutoGenerateDeleteButton="true"
    AutoGenerateInsertButton="true"
    AllowPaging="true"
    DataSourceID="LinqDataSource1"
    ID="GridView1" 
    >
</asp:DetailsView>
<asp:LinqDataSource 
    ContextTypeName="ExampleDataContext" 
    TableName="Products" 
    EnableUpdate="true"
    EnableInsert="true"
    EnableDelete="true"
    ID="LinqDataSource1" 
    >
</asp:LinqDataSource>
<asp:DetailsView 
    DataKeyNames="ProductID"
    AutoGenerateEditButton="true"
    AutoGenerateDeleteButton="true"
    AutoGenerateInsertButton="true"
    AllowPaging="true"
    DataSourceID="LinqDataSource1"
    ID="GridView1" 
    >
</asp:DetailsView>

Modificando Dados com o Controle ObjectDataSource

The ObjectDataSource control enables you to specify a data object method for performing a specific type of update.The InsertMethod property specifies the data object method that is called when the ObjectDataSource control inserts an item into the data source.Similarly, the UpdateMethod property specifies the data object method used for item updates, and the DeleteMethod property specifies the method used to delete an item from the data source.

The following code example shows an ObjectDataSource control with its InsertMethod, UpdateMethod, and DeleteMethod properties configured with the names of methods from the underlying data object.

<asp:ObjectDataSource 
  ID="EmployeeDetailsObjectDataSource" 
   
  TypeName="Samples.AspNet.Controls.NorthwindEmployee" 
  SelectMethod="GetEmployee" 
  UpdateMethod="UpdateEmployee"
  DeleteMethod="DeleteEmployee"
  InsertMethod="InsertEmployee" 
  OnInserted="EmployeeDetailsObjectDataSource_OnInserted" >
  <SelectParameters>
    <asp:Parameter Name="EmployeeID" />  
  </SelectParameters>
  <InsertParameters>
    <asp:Parameter Name="NewEmployeeID" Direction="Output" 
                   Type="Int32" DefaultValue="0" />
  </InsertParameters>
</asp:ObjectDataSource>
<asp:ObjectDataSource 
  ID="EmployeeDetailsObjectDataSource" 
   
  TypeName="Samples.AspNet.Controls.NorthwindEmployee" 
  SelectMethod="GetEmployee" 
  UpdateMethod="UpdateEmployee"
  DeleteMethod="DeleteEmployee"
  InsertMethod="InsertEmployee" 
  OnInserted="EmployeeDetailsObjectDataSource_OnInserted" >
  <SelectParameters>
    <asp:Parameter Name="EmployeeID" />  
  </SelectParameters>
  <InsertParameters>
    <asp:Parameter Name="NewEmployeeID" Direction="Output" 
                   Type="Int32" DefaultValue="0" />
  </InsertParameters>
</asp:ObjectDataSource>

Para obter mais informações, consulte Criando um objeto de origem de controle ObjectDataSource.

Modificando Dados com Comandos SQL

The SqlDataSource and AccessDataSource controls enable you to supply SQL commands for modifying data at the data source.The InsertCommand property specifies a SQL command to insert a record into the data source.Similarly, the UpdateCommand property specifies a command used for record updates, and the DeleteCommand property specifies a command used to delete a record from the data source.

The following code example shows a SqlDataSource control with its InsertCommand, UpdateCommand, and DeleteCommand properties configured with SQL commands that perform update tasks.

<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>
<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>

Para obter mais informações, consulte Modificando dados usando o controle SqlDataSource.

Parâmetros

Você pode fazer cenários de atualização de dados mais flexíveis, usando parâmetros para passar valores a serem inseridos, atualizados ou excluídos em um armazenamento de dados.Valores de parâmetro podem incluir os valores dos controles na página, as variáveis de aplicativo ASP.NET, valores de sessão e assim por diante.

Valores de parâmetro normalmente vêm de controles com dados vinculados quando esses controles chamam uma atualização, insere ou exclui a operação.Além disso, você pode criar objetos de parâmetro explícitos para controle de fonte de dados para uma operação determinada, que permite que você personalize os parâmetros.For example, you can use an explicit parameter object to specify the type or direction of a parameter, or to define a default value for a parameter in case a null value is passed.

For the ObjectDataSource control, parameter values are passed as arguments when calling the appropriate method of the underlying data object.For the SqlDataSource or AccessDataSource control, parameters are passed to the SQL command used for the update.Para mais informações e exemplos, consulte Usando parâmetros com controles de fonte de dados.

Eventos

Controles de fonte de dados aumentam ambos os eventos antes e depois dos dados serem modificados.Você pode usar esses eventos para executar código antes da operação de dados ocorrer, incluindo cancelar a operação, e após a operação de dados acontecer.For example, you can use the Deleting event of the SqlDataSource control to log information about a record about to be deleted.You can also use the Inserted event of the SqlDataSource control to retrieve an auto-generated identity value for the newly inserted record.

Consulte também

Outros recursos

Controles Servidores da Web com fonte de dados