插入和更新问题

时间:2013-04-08 02:16:35

标签: asp.net sql sql-server stored-procedures

我是ASP.NET / C#的菜鸟,但我会尽力尽力描述我的问题。

现在我有一个连接了sql源的gridview;它抓住了正确的信息。 gridview的信息将根据在网格外部的下拉列表中选择的内容而发生变化。问题在于更新和插入。

尝试更新后。 (当我在其中一列上单击编辑时)我收到以下错误消息:'DropDownList2'具有一个无效的SelectedValue,因为它在项目列表中不存在。 参数名称:值

我将列拆分为模板,如下所示,因此我可以更轻松地管理它们。 “下拉列表2”位于我的编辑模板中。它连接到数据源;这与我的第一个dropdownmenu完全一样,完美无缺。所以我不相信这将是该程序背后的sql。但我确实将此下拉列表2绑定到Doctor。     现在我被告知要绑定它,所以我不知道绑定是如何工作的

如果我取消绑定,我可以在单击编辑后至少看到网格,但在更新后我收到错误消息:过程或函数uspPatientUpdate指定了太多参数。

现在我已经在网上寻找解决方案,但我无法绕过绑定。我会根据需要提供以下代码。

ASP:

<asp:SqlDataSource ID="sdPatient" runat="server" ConnectionString="<%$ ConnectionStrings:MedicalOfficeConnectionString %>" DeleteCommand="usp_PatientDelete" InsertCommand="uspPatientInsert" SelectCommand="uspPatientSelectByIDOrSelectAll" UpdateCommand="uspPatientUpdate" SelectCommandType="StoredProcedure" DeleteCommandType="StoredProcedure" InsertCommandType="StoredProcedure" UpdateCommandType="StoredProcedure">
                <DeleteParameters>
                    <asp:Parameter Name="ID" Type="Int32" />
                </DeleteParameters>
                <InsertParameters>
                    <asp:Parameter Name="OHIP" Type="String" />
                    <asp:Parameter Name="FirstName" Type="String" />
                    <asp:Parameter Name="LastName" Type="String" />
                    <asp:Parameter DbType="Date" Name="DOB" />
                    <asp:Parameter Name="VisitsPerYear" Type="Int32" />
                    <asp:Parameter Name="DoctorID" Type="Int32" />
                    <asp:Parameter Name="Timestamp" Type="Byte"></asp:Parameter>
                </InsertParameters>
                <SelectParameters>
                    <asp:ControlParameter ControlID="DropDownList1" Name="DoctorID" PropertyName="SelectedValue" Type="Int32" DefaultValue="0" />
                </SelectParameters>
                <UpdateParameters>
                    <asp:Parameter Name="ID" Type="Int32" />
                    <asp:Parameter Name="OHIP" Type="String" />
                    <asp:Parameter Name="FirstName" Type="String" />
                    <asp:Parameter Name="LastName" Type="String" />
                    <asp:Parameter DbType="Date" Name="DOB" />
                    <asp:Parameter Name="VisitsPerYear" Type="Int32" />
                    <asp:Parameter Name="DoctorID" Type="Int32" />
                    <asp:Parameter Name="ID" Type="Int32" />
                    <asp:Parameter Name="Timestamp" Type="Byte"></asp:Parameter>
                </UpdateParameters>
            </asp:SqlDataSource>
            <p>Select Patient By Doctor:<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="sdDoctorList" DataTextField="Doctor" DataValueField="ID" AppendDataBoundItems="True">
                <asp:ListItem Value="0">All Doctors</asp:ListItem>
                </asp:DropDownList>
            <asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" DataSourceID="sdPatient" GridLines="Horizontal">
                    <Columns>
                        <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
                        <asp:TemplateField HeaderText="OHIP" SortExpression="OHIP">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("OHIP") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Bind("OHIP") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label2" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label3" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="DOB" SortExpression="DOB">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("DOB") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label4" runat="server" Text='<%# Bind("DOB") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Visits Per Year" SortExpression="VisitsPerYear">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("VisitsPerYear") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label5" runat="server" Text='<%# Bind("VisitsPerYear") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Doctor" SortExpression="Doctor">
                            <EditItemTemplate>
                                <asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="sdDoctorList" DataTextField="Doctor" DataValueField="ID"  SelectedValue='<%# Bind("Doctor") %>'>
                                </asp:DropDownList>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label6" runat="server" Text='<%# Bind("Doctor") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <FooterStyle BackColor="White" ForeColor="#333333" />
                    <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="White" ForeColor="#333333" />
                    <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
                    <SortedAscendingCellStyle BackColor="#F7F7F7" />
                    <SortedAscendingHeaderStyle BackColor="#487575" />
                    <SortedDescendingCellStyle BackColor="#E5E5E5" />
                    <SortedDescendingHeaderStyle BackColor="#275353" />
                </asp:GridView>

程序:

这是针对下拉列表的。这给出了名称和值。 *注意:此过程适用于第一个下拉列表,我想第二个下拉列表。

ALTER PROCEDURE dbo.uspDoctorList
AS
BEGIN
    SET NOCOUNT ON
    SELECT     ID, LastName +', ' + FirstName AS 'Doctor'
    FROM         Doctor
    ORDER BY 'Doctor'
END

这是更新程序。不确定这是否是错误的,或者它只是我的ASP

ALTER PROCEDURE dbo.uspPatientUpdate
    @ID int,
    @OHIP char(10),
    @FirstName nvarchar(20),
    @LastName nvarchar(40),
    @DOB date,
    @VisitsPerYear int,
    @DoctorID int,
    @Timestamp Timestamp

AS
BEGIN
    SET NOCOUNT OFF
    UPDATE Patient
    SET OHIP = @OHIP,
      FirstName = @FirstName, 
      LastName = @LastName,
      DOB = @DOB,
      VisitsPerYear = @VisitsPerYear,
      DoctorID = @DoctorID
    WHERE ID = @ID AND Timestamp = @Timestamp
END

我会感激任何帮助。顺便说一句,这个东西比我们教的东西(使用ASP中的存储过程)稍微提前一点,我要花费额外的奖励分数......提前谢谢。

如果您需要更多信息,请询问

2 个答案:

答案 0 :(得分:3)

问题1 - 更新gridview中的数据

1)正如Andriy所指出的,你的第一个问题是ID在<UpdateParameters>中被列出两次,删除其中一个。

2)从参数列表timestamps are updated automatically

中删除时间戳
    <UpdateParameters>
        <asp:Parameter Name="ID" Type="Int32" />
        <asp:Parameter Name="OHIP" Type="String" />
        <asp:Parameter Name="FirstName" Type="String" />
        <asp:Parameter Name="LastName" Type="String" />
        <asp:Parameter Name="DOB" DbType="DateTime" />
        <asp:Parameter Name="VisitsPerYear" Type="Int32" />
        <asp:Parameter Name="DoctorID" Type="Int32" />
    </UpdateParameters>

注意:如果需要保存日期时间戳,请在SQL中将时间戳列的数据类型更改为datetime并更改存储的更新程序为 - Patient.Timestamp = GETDATE()

3)从更新存储过程中删除@Timestamp(作为参数和WHERE子句)

4)在gridview集DataKeyNames="ID"的标记中,非常重要,使用DataKeyNames属性指定代表数据源主键的字段,必须设置它才能使GridView控件的自动更新和删除功能起作用:

<asp:GridView
            ID="GridView1"
            DataKeyNames="ID"

完成上述所有操作后,您的更新将会正常运行,我已经使用SQL Server Express 2008和ASP.NET 4.0为您创建了一个示例项目,您可以在Google驱动器上找到它here(只需点击文件 - &gt;下载即可获得.zip项目)

问题2 - 在gridview中插入数据并刷新

1)更改<InsertParameters>以从控件获取数据(我只显示了一个包含四个参数的示例,您可以根据需要进行更改)

<InsertParameters>
    <asp:ControlParameter ControlID="txtOhip" Name="OHIP" />
    <asp:ControlParameter ControlID="txtFirstName" Name="FirstName" />
    <asp:ControlParameter ControlID="txtLastName" Name="LastName" />
    <asp:ControlParameter ControlID="ddlDoctorId" Name="DoctorID" PropertyName="SelectedValue" />
</InsertParameters> 

2)向页面添加插入控件,并在用户单击添加按钮时调用sql数据源的Insert()方法:

<table>
    <tr>
        <td>
            OHIP
        </td>
        <td>
            <asp:TextBox ID="txtOhip" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            First name
        </td>
        <td>
            <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            Last name
        </td>
        <td>
            <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            Doctor
        </td>
        <td>
            :<asp:DropDownList ID="ddlDoctorId" runat="server" AutoPostBack="True" DataSourceID="sdDoctorList"
                DataTextField="Doctor" DataValueField="DoctorID" AppendDataBoundItems="True">
                <asp:ListItem Value="0">All Doctors</asp:ListItem>
            </asp:DropDownList>
        </td>
    </tr>
    <tr>
        <td style="text-align: right" colspan="2">
            <asp:Button ID="btnAdd" OnClick="Add" runat="server" Text="Add" />
        </td>
    </tr>
</table>
<script runat="server">
protected void Add(object sender,EventArgs e)
    {
        sdPatient.Insert();
    } 
</script>

答案 1 :(得分:1)

您的错误与下拉列表和与存储过程相关的参数有关 所以要用数据库中的数据绑定下拉列表 - (我通过认为你有使用三层的asp.net的基本知识来编写这段代码) 在Appcode文件夹中创建一个类并编写foll方法

**SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
private void Openconnection()
{
    if (con == null)
    {
        con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Nameofconn_defin in web.config file"].ConnectionString);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        cmd = new SqlCommand();
        cmd.Connection = con;
    }
}
private void Closeconnection()
{
    if (con.State == ConnectionState.Open)
    {
        con.Close();
    }
}
private void Disposeconnection()
{
    if (con != null)
    {
        con.Dispose();
        con = null;
    }
}

public DataTable GetDatatable(string strsql)     {         OpenConnection的();         DataTable dt = new DataTable();         cmd.CommandType = CommandType.Text;         cmd.CommandText = strsql;         cmd.CommandTimeout = 1000;         da = new SqlDataAdapter();         da.SelectCommand = cmd;         da.Fill(DT);         Closeconnection();         Disposeconnection();         返回;     }

比在ASPX.CS文件中写一个方法

public void BindBacecurrency()
    {
        try
        {
            string str = "select * from Currency_Master";
            DataTable dt = dut.GetDatatable(str);
            ddlbasecurrency.DataSource = dt;
            ddlbasecurrency.DataValueField = dt.Columns["Currency_Id"].ToString();
            ddlbasecurrency.DataTextField = dt.Columns["Currency_Name"].ToString();
            ddlbasecurrency.DataBind();
            ddlbasecurrency.Items.Insert(0, "-------Select-------");


        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString());
            ScriptManager.RegisterStartupScript(this, this.GetType(), "message", "<script> alert('System Error ! Contact Your Service Provider ');</script>", false);
        }
    }

手动绑定,即不是从数据库绑定,而是在设计页面的HTML页面中写入

<asp:DropDownList ID="ddBalanceType" runat="server"  BackColor="#AFC7C7" class ="small-field size5" >
               <asp:ListItem  Text="-------------Select-------------"></asp:ListItem>
               <asp:ListItem Value="1" Text="CR"></asp:ListItem>
               <asp:ListItem Value="0" Text="DR"></asp:ListItem>
            </asp:DropDownList>

我可以向您展示如何使用3层架构使用参数和代码进行更新但首先我必须知道您正在理解我的代码,或者无论如何检查以下代码中的gridview和存储过程可能对您有所帮助

 <asp:TemplateField HeaderText="Function" ItemStyle-HorizontalAlign="Center">
                        <ItemTemplate>
                            <asp:LinkButton ID="btnEdit" runat="server" ToolTip='<%# Eval("party_id") %>' onclick="btnEdit_Click" >Edit</asp:LinkButton>

                        </ItemTemplate>
                        <ItemStyle HorizontalAlign="Center" />
                    </asp:TemplateField>

------对于Edit Buton,请单击---------

       protected void btnEdit_Click(object sender, EventArgs e)
        {
            try
            {
                Blank();
                GridViewRow gvrows = (GridViewRow)(((Control)sender).NamingContainer);
                LinkButton linkbtn = (LinkButton)gvrows.FindControl("btnEdit");
    string PartyId = linkbtn.ToolTip.ToString();
     string Com = "SELECT * FROM Transport_Mode WHERE party_id = '" + PartyId.ToString() + "' ORDER BY mode_id ASC ";
                DataTable dt2 = dut.GetDatatable(Com);--check above method in bal class
}
}

--------存储过程的示例代码------

    USE [Aesthetics1]
GO
/****** Object:  StoredProcedure [dbo].[OSP_InsUpdBankMaster]    Script Date: 04/08/2013 17:55:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[OSP_InsUpdBankMaster]
(
    @Bank_id int =null,
    @Bank_name varchar(30) =null,
    @account_no varchar(20) =null,
    @holder_name varchar(40) =null,
    @Branch varchar(25) =null,
    @status int =null,
    @add_user varchar(8) =null,
    @Result int = 0output
)
AS
BEGIN
BEGIN TRANSACTION
    IF NOT EXISTS (SELECT 1 FROM Bank_master WHERE Bank_id = @Bank_id)
    BEGIN
        INSERT INTO Bank_master (Bank_name,account_no,holder_name,Branch,status,add_date,add_user) 
        VALUES (@Bank_name,@account_no,@holder_name,@Branch,@status,GETDATE(),@add_user)

        SET @Result = 1
    END
    ELSE IF EXISTS (SELECT 1 FROM Bank_master WHERE Bank_id = @Bank_id)
    BEGIN
        UPDATE Bank_master SET Bank_name = @Bank_name,
                                account_no = @account_no,
                                holder_name = @holder_name,
                                Branch = @Branch,
                                status = @status
                    where Bank_id = @Bank_id    
                SET @Result = 2
    END
IF @@ERROR = 0
COMMIT TRANSACTION
ELSE
BEGIN
    SET @Result = -1
    ROLLBACK TRANSACTION
END
END