1011 1110
1011 1110

Reputation: 781

Issue with inserts and updates

I am a noob at ASP.NET/C#, but I'll do my best to describe my problem as best as I can.

Now I have a gridview that has a sql source attached to it; It grabs the correct information. The gridview's information will change depending on what is selected in a dropdown list that is outside of the grid, which works. The problem lies within updating and inserting.

Once attempting to update. (AS soon as I click edit on one of the columns) I get the following error message: 'DropDownList2' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value

I split the columns into templates, as seen below,so I can manage them easier. 'Dropdown list 2' is located in my edit template. It is connected to a datasource; that being the exact same source as my first dropdownmenu which works flawlessly. So I don't believe it would be the sql behind that procedure. I do however have this dropdownlist 2 bound to Doctor. Now I was told to bound it, so I do not know how binding works

If I unbind it, I can at least see the grid still after I click edit, but after I update I get the error message: Procedure or function uspPatientUpdate has too many arguments specified.

Now I've looked online for a solution, but I can't wrap my head around binding. I'll give the following code as necessary.

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>

Procedures:

This is for the dropdownlists. This gives the name as well as the value. *Note: This procedure works for the first dropdownlist, and I suppose for the second one to.

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

This is the update procedure. Not sure if this is the one at fault or not, or if it is just my 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

I'll appreciate any help. BTW this stuff is a little more advance then what we were taught (using stored procedures in ASP), I'm going the extra mile for bonus marks.. Thanks in advance.

If you need any more information, please ask

Upvotes: 5

Views: 1552

Answers (2)

RajGauravJais
RajGauravJais

Reputation: 11

Your error are with dropdown and parameter related to stored procedure so to bind a drop down with data from database- (I am writing this code by thinking that you have the basic knowledge of asp.net using three tier) Make a class in Appcode folder and write foll method

**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(); return dt; }

Than in ASPX.CS FILE Write a method

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);
        }
    }

To bind it manually i.e Not from database ,than write in HTML Page of your Design Page

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

I can show you how to update using parameters and codes using 3 Tier Architecture but First i have to know that you are understanding my codes or not any way check the below code for gridview and stored procedure may this help you

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

------For Edit Buton click---------

       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
}
}

--------Sample code for stored procedure------

    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

Upvotes: 1

Denys Wessels
Denys Wessels

Reputation: 17017

Question 1 - Update data in gridview

1) As pointed out by Andriy your first problem is that the ID is listed twice in <UpdateParameters>,remove one of them.

2) Remove Timestamp from the list of parameters, 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>

NOTE: If you need to save date timestamps, in SQL change the datatype of the Timestamp column to datetime and change the Update stored procedure as - Patient.Timestamp = GETDATE()

3) Remove @Timestamp from the update stored procedure(both as a parameter and from the WHERE clause)

4) In the markup of the gridview set DataKeyNames="ID" this is very important, Use DataKeyNames property to specify the field that represents the primary key of the data source, it must be set in order for the automatic update and delete features of the GridView control to work:

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

Once you've done all of the above your updates will work, I've created a sample project for you using SQL Server Express 2008 and ASP.NET 4.0, you can find it here on Google drive (Just click on File -> Download to get the.zip project)

Question 2 - Insert data and refresh in gridview

1) Change <InsertParameters> to get data from controls (Im showing an example with only four parameters, you can change this as needed)

<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)Add insert controls to the page and call the Insert() method of your sql data source when the user clicks the add button:

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

Upvotes: 3

Related Questions