SqlDataSource.Inserting SqlDataSource.Inserting SqlDataSource.Inserting SqlDataSource.Inserting Event

定义

执行插入操作前发生。Occurs before an insert operation.

public:
 event System::Web::UI::WebControls::SqlDataSourceCommandEventHandler ^ Inserting;
public event System.Web.UI.WebControls.SqlDataSourceCommandEventHandler Inserting;
member this.Inserting : System.Web.UI.WebControls.SqlDataSourceCommandEventHandler 
Public Custom Event Inserting As SqlDataSourceCommandEventHandler 

示例

下面的代码示例演示如何从 Microsoft SQL Server 检索数据并在GridView控件中显示数据, 以及如何DetailsView使用控件以窗体的形式查看所选行GridView的详细信息, 并将其作为插入新记录的窗体。The following code example demonstrates how to retrieve data from Microsoft SQL Server and display it in a GridView control and how to use a DetailsView control to see details of a selected row in the GridView and as a form to insert new records.

备注

此示例演示如何使用声明性语法进行数据访问。This example shows how to use declarative syntax for data access. 有关如何使用代码而不是标记访问数据的信息, 请参阅在 Visual Studio 中访问数据For information about how to access data by using code instead of markup, see Accessing data in Visual Studio.

最初, 数据显示在GridView控件中, 所选行GridView还显示在DetailsView控件中。Initially, the data is displayed in the GridView control, and the selected row of the GridView is also displayed in the DetailsView control. FilterExpression DetailsView FilterParameters GridView和控件使用不同的数据源控件; 与关联的控件具有和属性, 这可确保的选定行为DetailsView GridView会.The GridView and DetailsView controls use different data source controls; the one that is associated with the DetailsView has the FilterExpression and FilterParameters properties, which ensures that the selected row of the GridView is displayed.

如果单击DetailsView控件的自动生成的插入按钮, 则DetailsView会显示一个不同的用户界面, 用于插入新记录。If you click the automatically generated Insert button of the DetailsView control, the DetailsView shows a different user interface, which is used to insert a new record. 该示例使用存储过程插入记录, 并返回插入行的主键。The example uses a stored procedure to insert records and returns the primary key of the inserted row. 如果插入记录, 将DetailsView使用Insert绑定列中的InsertParameters值自动填充集合, 并调用方法。If you insert a record, the DetailsView automatically populates the InsertParameters collection with values from the bound columns and calls the Insert method. 当使用 ASP.NET 双向数据绑定语法时BoundField ,可以从任何对象推断正确的参数,并为提供一个参数。DetailsView TemplateFieldThe DetailsView can infer the correct parameters from any BoundField object and a parameter for the TemplateField when the ASP.NET two-way data-binding syntax is used. 在此示例中, 会在OnInserting事件处理程序中添加一个附加参数, 用于处理存储过程返回的主键。In this example, an additional parameter is added in the OnInserting event handler to handle the primary key that is returned by the stored procedure.

最后, 在DetailsView控件将数据插入到数据库OnInserted中后, 将调用事件处理程序来处理Inserted事件, 插入行的主键的值将显示, 并使用DataBind GridView显式调用控件来刷新数据。Finally, after data is inserted into the database by the DetailsView control, the OnInserted event handler is called to handle the Inserted event, the value of the primary key of the inserted row is displayed, and the DataBind method of the GridView control is called explicitly to refresh the data.

<%@Page  Language="C#" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<%@Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
 private void On_Inserting(Object sender, SqlDataSourceCommandEventArgs e) {

    SqlParameter insertedKey = new SqlParameter("@PK_New", SqlDbType.Int);
    insertedKey.Direction    = ParameterDirection.Output;        
    e.Command.Parameters.Add(insertedKey);
 }

 private void On_Inserted(Object sender, SqlDataSourceStatusEventArgs e) {
    DbCommand command = e.Command;    
    
    // The label displays the primary key of the recently inserted row.
    Label1.Text = command.Parameters["@PK_New"].Value.ToString();
    
    // Force a refresh after the data is inserted.
    GridView1.DataBind();
 }
</script>

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

      <asp:GridView
        id="GridView1"
        runat="server"
        AutoGenerateColumns="False"
        DataKeyNames="EmployeeID"        
        DataSourceID="SqlDataSource1">
        <columns>          
          <asp:BoundField HeaderText="First Name" DataField="FirstName" />
          <asp:BoundField HeaderText="Last Name" DataField="LastName" />
          <asp:BoundField HeaderText="Title" DataField="Title" />
          <asp:ButtonField ButtonType="Link" CommandName="Select" Text="Details..." />
        </columns>
      </asp:GridView>

      <asp:SqlDataSource
        id="SqlDataSource1"
        runat="server"
        ConnectionString="<%$ ConnectionStrings:MyNorthwind %>"
        SelectCommand="SELECT EmployeeID,FirstName,LastName,Title FROM Employees">
      </asp:SqlDataSource>

      <hr />

      <asp:DetailsView
        id="DetailsView1"
        runat="server"
        DataSourceID="SqlDataSource2"
        AutoGenerateRows="False"
        AutoGenerateInsertButton="True">
        <fields>
          <asp:BoundField HeaderText="First Name" DataField="FirstName" ReadOnly="False"/>
          <asp:BoundField HeaderText="Last Name" DataField="LastName" ReadOnly="False"/>
          <asp:TemplateField HeaderText="Title">
            <ItemTemplate>
              <asp:DropDownList
                id="TitleDropDownList"
                runat="server"
                selectedvalue="<%# Bind('Title') %>" >
                <asp:ListItem Selected="True">Sales Representative</asp:ListItem>
                <asp:ListItem>Sales Manager</asp:ListItem>
                <asp:ListItem>Vice President, Sales</asp:ListItem>
              </asp:DropDownList>
            </ItemTemplate>
          </asp:TemplateField>
          <asp:BoundField HeaderText="Notes" DataField="Notes" ReadOnly="False"/>
        </fields>
      </asp:DetailsView>


      <asp:SqlDataSource
        id="SqlDataSource2"
        runat="server"
        ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
        SelectCommand="SELECT * FROM Employees"
        InsertCommandType = "StoredProcedure"
        InsertCommand="sp_insertemployee"        
        OnInserting="On_Inserting"
        OnInserted ="On_Inserted"
        FilterExpression="EmployeeID={0}">
        <FilterParameters>
          <asp:ControlParameter Name="EmployeeID" ControlId="GridView1" PropertyName="SelectedValue" />
        </FilterParameters>
      </asp:SqlDataSource>

<!-- 
     -- An example sp_insertemployee stored procedure that returns
     -- the primary key of the row that was inserted in an OUT parameter.
     CREATE PROCEDURE sp_insertemployee 
        @FirstName nvarchar(10), 
        @LastName nvarchar(20) , 
        @Title nvarchar(30), 
        @Notes nvarchar(200), 
        @PK_New int OUTPUT
      AS
        INSERT INTO Employees(FirstName,LastName,Title,Notes)VALUES (@FirstName,@LastName,@Title,@Notes)
        SELECT @PK_New = @@IDENTITY
        RETURN (1)    
      GO
-->      

      <asp:Label 
        id="Label1"
        runat="server" />
      
    </form>
  </body>
</html>
<%@Page  Language="VB" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<%@Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

 Sub On_Inserting(ByVal sender As Object, ByVal e As SqlDataSourceCommandEventArgs)

    Dim insertedKey As SqlParameter  
    insertedKey = New SqlParameter("@PK_New", SqlDbType.Int)
    insertedKey.Direction    = ParameterDirection.Output     
    
    e.Command.Parameters.Add(insertedKey)

 End Sub 'On_Inserting

 Sub On_Inserted(ByVal sender As Object, ByVal e As SqlDataSourceStatusEventArgs)
    Dim command As DbCommand 
    command = e.Command
    
    ' The label displays the primary key of the recently inserted row.
    Label1.Text = command.Parameters("@PK_New").Value.ToString()    
    
    ' Explicitly call DataBind to refresh the data
    ' and show the newly inserted row.
    GridView1.DataBind()
 End Sub 'On_Inserted

</script>

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

      <asp:GridView
        id="GridView1"
        runat="server"
        AutoGenerateColumns="False"
        DataKeyNames="EmployeeID"        
        DataSourceID="SqlDataSource1">
        <columns>          
          <asp:BoundField HeaderText="First Name" DataField="FirstName" />
          <asp:BoundField HeaderText="Last Name" DataField="LastName" />
          <asp:BoundField HeaderText="Title" DataField="Title" />
          <asp:ButtonField ButtonType="Link" CommandName="Select" Text="Details..." />
        </columns>
      </asp:GridView>

      <asp:SqlDataSource
        id="SqlDataSource1"
        runat="server"
        ConnectionString="<%$ ConnectionStrings:MyNorthwind %>"
        SelectCommand="SELECT EmployeeID,FirstName,LastName,Title FROM Employees">
      </asp:SqlDataSource>

      <hr />

      <asp:DetailsView
        id="DetailsView1"
        runat="server"
        DataSourceID="SqlDataSource2"
        AutoGenerateRows="False"
        AutoGenerateInsertButton="True">
        <fields>
          <asp:BoundField HeaderText="First Name" DataField="FirstName" ReadOnly="False"/>
          <asp:BoundField HeaderText="Last Name" DataField="LastName" ReadOnly="False"/>
          <asp:TemplateField HeaderText="Title">
            <ItemTemplate>
              <asp:DropDownList
                id="TitleDropDownList"
                runat="server"
                selectedvalue="<%# Bind('Title') %>" >
                <asp:ListItem Selected="True">Sales Representative</asp:ListItem>
                <asp:ListItem>Sales Manager</asp:ListItem>
                <asp:ListItem>Vice President, Sales</asp:ListItem>
              </asp:DropDownList>
            </ItemTemplate>
          </asp:TemplateField>
          <asp:BoundField HeaderText="Notes" DataField="Notes" ReadOnly="False"/>
        </fields>
      </asp:DetailsView>


      <asp:SqlDataSource
        id="SqlDataSource2"
        runat="server"
        ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
        SelectCommand="SELECT * FROM Employees"
        InsertCommandType = "StoredProcedure"
        InsertCommand="sp_insertemployee"        
        OnInserting="On_Inserting"
        OnInserted ="On_Inserted"
        FilterExpression="EmployeeID={0}">
        <FilterParameters>
          <asp:ControlParameter Name="EmployeeID" ControlId="GridView1" PropertyName="SelectedValue" />
        </FilterParameters>
      </asp:SqlDataSource>

<!-- 
     -- An example sp_insertemployee stored procedure that returns
     -- the primary key of the row that was inserted in an OUT parameter.
     CREATE PROCEDURE sp_insertemployee 
        @FirstName nvarchar(10), 
        @LastName nvarchar(20) , 
        @Title nvarchar(30), 
        @Notes nvarchar(200), 
        @PK_New int OUTPUT
      AS
        INSERT INTO Employees(FirstName,LastName,Title,Notes)VALUES (@FirstName,@LastName,@Title,@Notes)
        SELECT @PK_New = @@IDENTITY
        RETURN (1)    
      GO
-->      

      <asp:Label 
        id="Label1"
        runat="server" />
      
    </form>
  </body>
</html>

注解

处理事件以执行其他特定于应用程序的初始化操作, 验证参数的值, 或者在SqlDataSource控件执行插入操作之前更改参数值。 InsertingHandle the Inserting event to perform additional initialization operations that are specific to your application, to validate the values of parameters, or to change the parameter values before the SqlDataSource control performs the insert operation. 在调用事件处理程序委托时, 与基础数据源的连接尚未打开。The connection to the underlying data source is not yet open when the event handler delegate is called. 因此, 您不能直接通过Cancel DbCommandSqlDataSourceCommandEventArgs属性公开的对象调用方法来取消操作。Therefore, you cannot cancel the operation directly by calling the Cancel method on the DbCommand object that is exposed by the SqlDataSourceCommandEventArgs property. 但是, 您可以通过将Cancel SqlDataSourceCommandEventArgs对象的属性设置为来true取消数据库操作。You can, however, cancel the database operation by setting the Cancel property of the SqlDataSourceCommandEventArgs object to true.

有关如何处理事件的详细信息, 请参阅处理和引发事件For more information about how to handle events, see Handling and Raising Events.

适用于

另请参阅