SqlDataSource.InsertCommand Proprietà
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Ottiene o imposta la stringa SQL utilizzata dal controllo SqlDataSource per inserire dati nel database sottostante.
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
Valore della proprietà
Stringa SQL utilizzata da SqlDataSource per inserire dati.
Esempio
In questa sezione sono riportati due esempi di codice. Il primo esempio di codice illustra come inserire dati in un database usando il SqlDataSource controllo e una semplice pagina di Web Forms. Il secondo esempio di codice illustra come recuperare dati da Microsoft SQL Server e visualizzarlo in un GridView controllo e come usare un DetailsView controllo per visualizzare i dettagli di una riga selezionata nel GridView controllo e come modulo per inserire nuovi record.
Nota
Questi esempi illustrano come usare la sintassi dichiarativa per l'accesso ai dati. Per informazioni su come accedere ai dati usando codice anziché markup, vedere Accesso ai dati in Visual Studio.
Nell'esempio di codice seguente viene illustrato come inserire dati in un database usando il SqlDataSource controllo e una semplice pagina di Web Forms. I dati correnti nella tabella Dati vengono visualizzati nel DropDownList controllo. È possibile aggiungere nuovi record immettendo i valori nei TextBox controlli e quindi facendo clic sul pulsante Inserisci . Quando si fa clic sul pulsante Inserisci , i valori specificati vengono inseriti nel database e il DropDownList controllo viene aggiornato.
Importante
Questo esempio include una casella di testo che accetta l'input utente, ovvero una potenziale minaccia di sicurezza e i valori vengono inseriti in parametri senza convalida, che è anche una potenziale minaccia di sicurezza. Usare l'evento Inserting per convalidare i valori dei parametri prima di eseguire la query. Per altre informazioni, vedere Cenni preliminari sugli attacchi tramite script.
<%@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>
Nell'esempio di codice seguente viene illustrato come recuperare dati da SQL Server e visualizzarlo in un GridView controllo e come usare un DetailsView controllo per visualizzare i dettagli di una riga selezionata nel GridView controllo e come modulo per inserire nuovi record.
Inizialmente, i dati vengono visualizzati nel GridView controllo e la riga selezionata dell'oggetto GridView viene visualizzata anche nel DetailsView controllo. I GridView controlli e DetailsView usano controlli di origine dati diversi, ovvero quello associato alle DetailsViewFilterExpression proprietà e FilterParameters , che garantisce che venga visualizzata la riga selezionata dell'oggetto GridView .
Se si fa clic sul pulsante Inserisci generato automaticamente del DetailsView controllo, viene DetailsView visualizzata un'interfaccia utente diversa, utilizzata per inserire un nuovo record. Nell'esempio viene usata una stored procedure per inserire record e restituisce la chiave primaria della riga inserita. Se si inserisce un record, l'insieme DetailsViewInsertParameters viene popolato automaticamente con valori dalle colonne associate e chiama il Insert metodo . Può DetailsView dedurre i parametri corretti da qualsiasi BoundField oggetto e un parametro per l'oggetto TemplateField quando viene usata la sintassi di data binding bidirezionale ASP.NET. In questo esempio viene aggiunto un parametro aggiuntivo nel OnInserting gestore eventi per gestire la chiave primaria restituita dalla stored procedure.
Infine, dopo l'inserimento dei dati nel database dal DetailsView controllo, il gestore eventi viene chiamato per gestire l'eventoInserted, il OnInserted valore della chiave primaria della riga inserita viene visualizzato e il DataBind metodo del GridView controllo viene chiamato in modo esplicito per aggiornare i dati.
<%@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>
Commenti
Rappresenta InsertCommand una query SQL o il nome di una stored procedure e viene usato dal Insert metodo .
Poiché il tipo di SQL utilizzato varia a seconda dei prodotti del database, la sintassi della stringa SQL dipende dal provider ADO.NET attualmente in uso, il quale è identificato dalla proprietà ProviderName. Se la stringa SQL è una query o un comando con parametri, anche il segnaposto del parametro dipenderà dal provider ADO.NET in uso. Ad esempio, se il provider è , System.Data.SqlClientche è il provider predefinito per la SqlDataSource classe, il segnaposto del parametro è '@parameterName'
. Tuttavia, se il provider è impostato su System.Data.Odbc o System.Data.OleDb, il segnaposto del parametro è '?'
. Per altre informazioni sulle query e i comandi SQL con parametri, vedere Uso di parametri con il controllo SqlDataSource.
Può InsertCommand essere una stringa SQL o il nome di una stored procedure, se l'origine dati supporta stored procedure.
Questa proprietà delega alla InsertCommand proprietà dell'oggetto SqlDataSourceView associato al SqlDataSource controllo.
Importante
A scopo di sicurezza, la InsertCommand proprietà non viene archiviata è lo stato di visualizzazione. Poiché è possibile decodificare il contenuto dello stato di visualizzazione nel client, l'archiviazione di informazioni riservate sulla struttura del database nello stato di visualizzazione potrebbe causare una vulnerabilità di divulgazione delle informazioni.
Importante
I valori vengono inseriti nei parametri senza convalida, ovvero una potenziale minaccia di sicurezza. Usare l'evento Filtering per convalidare i valori dei parametri prima di eseguire la query. Per altre informazioni, vedere Cenni preliminari sugli attacchi tramite script.
Si applica a
Vedi anche
Commenti e suggerimenti
https://aka.ms/ContentUserFeedback.
Presto disponibile: Nel corso del 2024 verranno gradualmente disattivati i problemi di GitHub come meccanismo di feedback per il contenuto e ciò verrà sostituito con un nuovo sistema di feedback. Per altre informazioni, vedereInvia e visualizza il feedback per