SqlDataSource.Inserted 이벤트

정의

삽입 작업이 완료되면 발생합니다.Occurs when an insert operation has completed.

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

이벤트 유형

SqlDataSourceStatusEventHandler

예제

다음 코드 예제에는 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. GridViewDetailsView 다양 한 데이터를 사용 하 여 컨트롤 소스 컨트롤; 연결 된 것을 DetailsViewFilterExpressionFilterParameters 의 선택된 된 행 되도록 하는 속성을는 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 자동으로 채웁니다 합니다 InsertParameters 호출 고 바인딩된 열에서 값을 사용 하 여 컬렉션을 Insert 메서드.If you insert a record, the DetailsView automatically populates the InsertParameters collection with values from the bound columns and calls the Insert method. 합니다 DetailsView 에서 올바른 매개 변수를 유추할 수 있습니다 BoundField 개체 및에 대 한 매개 변수는 TemplateField 양방향 ASP.NET 데이터 바인딩 구문을 사용 하는 경우 개체입니다.The DetailsView can infer the correct parameters from any BoundField object and a parameter for the TemplateField object 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>

설명

처리는 Inserted 삽입 작업이 완료 된 후의 값을 확인 하려면 출력 매개 변수입니다.Handle the Inserted event to examine the values of output parameters after an insert operation has completed. 출력 매개 변수에서 사용할 수는 SqlDataSourceStatusEventArgs 이벤트와 연결 된 개체입니다.The output parameters are available from the SqlDataSourceStatusEventArgs object that is associated with the event.

이벤트를 처리 하는 방법에 대 한 자세한 내용은 참조 하세요. 이벤트 처리 및 발생합니다.For more information about how to handle events, see Handling and Raising Events.

적용 대상

추가 정보