SqlDataSourceView.InsertCommand Свойство

Определение

Получает или задает SQL-строку, которая используется объектом SqlDataSourceView для вставки данных в основную базу данных.

public:
 property System::String ^ InsertCommand { System::String ^ get(); void set(System::String ^ value); };
public string InsertCommand { get; set; }
member this.InsertCommand : string with get, set
Public Property InsertCommand As String

Значение свойства

SQL-строка, используемая объектом SqlDataSourceView для вставки данных.

Примеры

Этот раздел содержит два примера кода. В первом примере кода показано, как вставить данные в базу данных с помощью SqlDataSource элемента управления . Во втором примере кода показано, как получить данные из microsoft SQL Server, отобразить их в элементе GridView управления и использовать DetailsView элемент управления для просмотра сведений о выбранной строке в и в GridView виде формы для вставки новых записей.

В следующем примере кода показано, как вставить данные в базу данных с помощью SqlDataSource элемента управления . Текущие данные в таблице отображаются в элементе DropDownList управления . Вы можете добавить новые записи, введя значения в TextBox элементах управления и нажав кнопку Вставка . При нажатии кнопки Вставка указанные значения вставляются в базу данных, а DropDownList объект обновляется.

<%@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">
private void InsertShipper (object source, EventArgs e) {
  SqlDataSource1.Insert();
}
</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:dropdownlist
        id="DropDownList1"
        runat="server"
        datasourceid="SqlDataSource1"
        datatextfield="CompanyName"
        datavaluefield="ShipperID" />

<!-- Security Note: The SqlDataSource uses a FormParameter,
     Security Note: which does not perform validation of input from the client.
     Security Note: To validate the value of the FormParameter, handle the Inserting event. -->

      <asp:sqldatasource
        id="SqlDataSource1"
        runat="server"
        connectionstring="<%$ ConnectionStrings:MyNorthwind %>"
        selectcommand="SELECT CompanyName,ShipperID FROM Shippers"
        insertcommand="INSERT INTO Shippers (CompanyName,Phone) VALUES (@CoName,@Phone)">
          <insertparameters>
            <asp:formparameter name="CoName" formfield="CompanyNameBox" />
            <asp:formparameter name="Phone"  formfield="PhoneBox" />
          </insertparameters>
      </asp:sqldatasource>

      <br /><asp:textbox
           id="CompanyNameBox"
           runat="server" />

      <asp:RequiredFieldValidator
        id="RequiredFieldValidator1"
        runat="server"
        ControlToValidate="CompanyNameBox"
        Display="Static"
        ErrorMessage="Please enter a company name." />

      <br /><asp:textbox
           id="PhoneBox"
           runat="server" />

      <asp:RequiredFieldValidator
        id="RequiredFieldValidator2"
        runat="server"
        ControlToValidate="PhoneBox"
        Display="Static"
        ErrorMessage="Please enter a phone number." />

      <br /><asp:button
           id="Button1"
           runat="server"
           text="Insert New Shipper"
           onclick="InsertShipper" />

    </form>
  </body>
</html>
<%@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">
Private Sub InsertShipper (ByVal Source As Object, ByVal e As EventArgs)
  SqlDataSource1.Insert()
End Sub ' InsertShipper
</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:dropdownlist
        id="DropDownList1"
        runat="server"
        datasourceid="SqlDataSource1"
        datatextfield="CompanyName"
        datavaluefield="ShipperID" />

<!-- Security Note: The SqlDataSource uses a FormParameter,
     Security Note: which does not perform validation of input from the client.
     Security Note: To validate the value of the FormParameter, handle the Inserting event. -->

      <asp:sqldatasource
        id="SqlDataSource1"
        runat="server"
        connectionstring="<%$ ConnectionStrings:MyNorthwind %>"
        selectcommand="SELECT CompanyName,ShipperID FROM Shippers"
        insertcommand="INSERT INTO Shippers (CompanyName,Phone) VALUES (@CoName,@Phone)">
          <insertparameters>
            <asp:formparameter name="CoName" formfield="CompanyNameBox" />
            <asp:formparameter name="Phone"  formfield="PhoneBox" />
          </insertparameters>
      </asp:sqldatasource>

      <br /><asp:textbox
           id="CompanyNameBox"
           runat="server" />

      <asp:RequiredFieldValidator
        id="RequiredFieldValidator1"
        runat="server"
        ControlToValidate="CompanyNameBox"
        Display="Static"
        ErrorMessage="Please enter a company name." />

      <br /><asp:textbox
           id="PhoneBox"
           runat="server" />

      <asp:RequiredFieldValidator
        id="RequiredFieldValidator2"
        runat="server"
        ControlToValidate="PhoneBox"
        Display="Static"
        ErrorMessage="Please enter a phone number." />

      <br /><asp:button
           id="Button1"
           runat="server"
           text="Insert New Shipper"
           onclick="InsertShipper" />

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

В следующем примере кода показано, как получить данные из SQL Server, отобразить их в элементе GridView управления и использовать DetailsView элемент управления для просмотра сведений о выбранной строке GridView в и как форму для вставки новых записей.

Изначально данные отображаются в элементе GridView управления , а выбранная строка GridView также отображается в элементе DetailsView управления . Элементы GridView управления и DetailsView используют разные элементы управления источником данных. Связанный с DetailsView элементом управления имеет FilterExpression свойства и FilterParameters , которые обеспечивают отображение выбранной GridView строки .

Если нажать автоматически созданную кнопку DetailsViewВставка элемента управления, DetailsView отобразится другой пользовательский интерфейс, который используется для вставки новой записи. В примере используется хранимая процедура для вставки записей и возвращает первичный ключ вставленной строки. При вставке записи DetailsView объект автоматически заполняет коллекцию InsertParameters значениями из привязанных столбцов и вызывает Insert метод . Может DetailsView вывести правильные параметры из любого BoundField объекта и параметра для TemplateField объекта, если используется ASP.NET синтаксис двусторонней привязки данных. В этом примере в OnInserting обработчик событий добавляется дополнительный параметр для обработки первичного ключа, возвращаемого хранимой процедурой.

Наконец, после вставки данных элементом DetailsView управления в базу данных OnInserted вызывается обработчик событий для обработки Inserted события, отображается значение первичного ключа вставленной строки, а DataBind метод GridView элемента управления вызывается явным образом для обновления данных.

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

Комментарии

Различные системы баз данных используют различные диалекты SQL, поэтому синтаксис строки SQL зависит от используемого в данный момент поставщика ADO.NET, который определяется свойством ProviderName. Если строка SQL представляет собой параметризованный запрос или команду, заполнитель параметра также зависит от используемого поставщика ADO.NET. Например, если поставщиком является System.Data.SqlClient, который является поставщиком по умолчанию для SqlDataSource класса, заполнитель параметра — '@parameterName'. Однако если для поставщика задано System.Data.Odbc значение или System.Data.OleDb, заполнителем параметра является '?'. Дополнительные сведения о параметризованных запросах и командах SQL см. в статье Использование параметров с элементом управления SqlDataSource.

Свойство InsertCommand может быть строкой SQL или именем хранимой процедуры, если источник данных поддерживает хранимые процедуры.

Значение InsertCommand свойства хранится в состоянии представления.

Применяется к

См. также раздел