简体   繁体   中英

How to insert into a table using SqlDataSource & Parameters in ASP.NET?

I've been having troubles trying to get a little bit of code to work. I have an ASP.NET site that is set to update a database when the user picks two values and clicks a button. Then the SqlDataSource is supposed to execute a stored procedure that will insert into the database the two values and the current user's UserName .

But for some reason, I just can't get it to work correctly. No flags are popping up, but the database doesn't seem to be receiving any data. Hoping anyone can help, here is the relevant code:

My table:

CREATE TABLE [dbo].[Prescriptions] 
(
    [Prescription_ID]  INT           IDENTITY (1, 1) NOT NULL,
    [Doctor_UserName]  NVARCHAR (50) NOT NULL,
    [Patient_UserName] NVARCHAR (50) NOT NULL,
    [Drug_ID]          INT           NOT NULL,
    PRIMARY KEY CLUSTERED ([Prescription_ID] ASC)
);

The stored procedure:

CREATE PROCEDURE [dbo].[AddPrescription]
    @doctor nvarchar(50),
    @patient nvarchar(50),
    @drug nvarchar(MAX)
AS
    INSERT INTO dbo.Prescriptions (Doctor_UserName, Patient_UserName, Drug_ID)
        SELECT @doctor, @patient, d.Drug_ID
        FROM dbo.Drug AS d
        WHERE d.Trade_Name = @drug

Asp.Net code:

<asp:SqlDataSource ID="SqlDataSource3" runat="server" 
     ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" 
     SelectCommand="AddPrescription" SelectCommandType="StoredProcedure">
     <SelectParameters>
        <asp:Parameter Name="doctor" Type="String" />
        <asp:ControlParameter ControlID="PatientDropDown" Name="patient" 
             PropertyName="SelectedValue" Type="String" />
        <asp:ControlParameter ControlID="PrescriptionDropDown" Name="drug" 
             PropertyName="SelectedValue" Type="String" />
     </SelectParameters>
</asp:SqlDataSource>

Code behind for the button click:

protected void CreatePrescriptionBtn_Click(object sender, EventArgs e)
{
    SqlDataSource3.SelectParameters["doctor"].DefaultValue = System.Web.HttpContext.Current.User.Identity.Name.ToString();
    SqlDataSource3.DataBind();
}

Rebuild your SQL DataSource, select "Specify a custom SQL statement or stored procedure"

You should get to this screen: 在此处输入图片说明

Here is a crude, simple sample of what it should look like:

   <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>"
             SelectCommand="SELECT [ID], [CustomerName], [Population] FROM [TestTable]"
             InsertCommand="byroyalty" InsertCommandType="StoredProcedure">
            <InsertParameters>
                <asp:Parameter Name="percentage" Type="Int32" />
            </InsertParameters>
        </asp:SqlDataSource>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM