Link to home
Create AccountLog in
Avatar of sammySeltzer
sammySeltzerFlag for United States of America

asked on

Gridview Update command not updating all records, urgent PLEASE!!!

Greetings again, mates,

I have my application go LIVE today, a very highly visible application.

However, the users are not able to edit their records for whatever reason.

What they tell us is that they are able to edit ONLY the first row. No other rows edit.

They make their changes, click update but instead of updatting, the cursor moves to next record.

Can you please, please take a look and help figure out what could be wrong?

I can't find it and I have been looking at this now for 2 hours.

Many, many thanks for your kind and urgent response.

Here is the real code:

        <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" 
            AutoGenerateColumns="False" DataKeyNames="ID" AllowPaging="True" 
            CellPadding="4" ForeColor="#333333" GridLines="None" Visible="True" 
            OnRowDataBound="gvRowDataBound" OnRowUpdated="GridView1_RowUpdated" AutoGenerateEditButton="True">
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" Visible = "false"
                    ReadOnly="True" SortExpression="ID" />
                <asp:BoundField DataField="charity_code" HeaderText="Charity Code" 
                    SortExpression="charity_code" />
                <asp:BoundField DataField="chcknum" HeaderText="Check Number" 
                    SortExpression="chcknum" />
                <asp:BoundField DataField="check_amt" HeaderText="Check Amount" DataFormatString="{0:c2}" 
                    SortExpression="check_amt" />
                <asp:BoundField DataField="one_time" HeaderText="One Time Amount" DataFormatString="{0:c2}" 
                    SortExpression="one_time" />
                <asp:BoundField DataField="bi_weekly" HeaderText="Bi-Weekly Amount" DataFormatString="{0:c2}" 
                    SortExpression="bi_weekly" />
                <asp:BoundField DataField="cash" HeaderText="Cash Amount" SortExpression="cash" DataFormatString="{0:c2}" />
                <asp:BoundField DataField="donate_choice" HeaderText="Donate" ReadOnly = "true"
                    SortExpression="donate_choice" />
                <asp:BoundField DataField="date_stamp" HeaderText="Entry Date" ReadOnly = "true"
                    SortExpression="date_stamp" />
            </Columns>
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#999999" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
           </asp:GridView>
           <asp:HiddenField ID="dchide" runat="server" ></asp:HiddenField>
           <asp:HiddenField ID="idhide" runat="server" ></asp:HiddenField>
           <asp:HiddenField ID="ssnhide" runat="server" ></asp:HiddenField>
           <asp:HiddenField ID="pledgehide" runat="server" ></asp:HiddenField>
           <asp:HiddenField ID="idapp" runat="server" ></asp:HiddenField>
           <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:Database_DBConnectionString %>" 
            SelectCommand=" SELECT DA.ID, DA.employee_ID, DA.charity_code, CASE WHEN isnull(DA.chcknum, '')  = '' AND isnull(cash, 0) <> 0 THEN 'Cash Payment' ELSE chcknum END As chcknum, DA.check_amt, DA.one_time, DA.bi_weekly, DA.cash, DA.donate_choice, DA.date_stamp, DA.amb_approved, AE.dept_code, AE.empl_first, AE.empl_last
                          FROM employee_ded_amts as DA INNER JOIN active_empl as AE ON DA.employee_ID = AE.employee_id
                          WHERE (AE.dept_code = @dchide and AE.pledged=@pledgehide AND (DA.cash <> 0 or DA.check_amt <> 0)) ORDER BY DA.employee_ID" 
            UpdateCommand="UPDATE [employee_ded_amts] SET [charity_code] = @charity_code, [chcknum] = @chcknum, [check_amt] = @check_amt, [one_time] = @one_time, [bi_weekly] = @bi_weekly, [cash] = @cash,  [amb_approved] = @amb_approved WHERE [ID] = @ID">
            <UpdateParameters>
                <asp:Parameter Name="employee_ID" Type="String" />
                <asp:Parameter Name="charity_code" Type="String" />
                <asp:Parameter Name="chcknum" Type="String" />
                <asp:Parameter Name="check_amt" Type="Decimal" />
                <asp:Parameter Name="one_time" Type="Decimal" />
                <asp:Parameter Name="bi_weekly" Type="Decimal" />
                <asp:Parameter Name="cash" Type="Decimal" />
                <asp:Parameter Name="donate_choice" Type="String" />
                <asp:Parameter Name="date_stamp" Type="DateTime" />
                <asp:Parameter Name="amb_approved" Type="String" />
                <asp:Parameter Name="ID" Type="Int32" />
            </UpdateParameters>

Open in new window

SOLUTION
Avatar of Easwaran Paramasivam
Easwaran Paramasivam
Flag of India image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of sammySeltzer

ASKER

No, no luck.

Thanks for responding .

Any other ideas?
Could you share your Code behind file as well?
Add ProviderName="System.Data.SqlClient" attribute to asp:SqlDataSource
Add ProviderName="System.Data.SqlClient" attribute to asp:SqlDataSource

Can you please explain what you mean here?

Here is codebehind.

My biggest issue is that I didn't write this code and I am having difficulty finding out what needs to change.

It is a little confusing. Hopefully, you can bear with me.

Thanks for your help and patience:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        SqlDataSource2.SelectParameters("empl_last").DefaultValue = Session.Item("UserName").ToString
        SqlDataSource2.SelectParameters("empl_ssn").DefaultValue = Session.Item("Password").ToString
        SqlDataSource1.SelectParameters("dchide").DefaultValue = Session.Item("dept_code").ToString
        SqlDataSource1.SelectParameters("pledgehide").DefaultValue = Session.Item("pledged").ToString
        SqlDataSource1.DataBind()

    End Sub

    Protected Sub gvOnDataBound2(ByVal sender As Object, ByVal e As System.EventArgs)
        SqlDataSource1.DataBind()
        Dim deptcode As Label = FormView1.FindControl("dept_codeLabel")
        Dim dchide As HiddenField = form1.FindControl("dchide")
        Dim pledgehide As HiddenField = form1.FindControl("pledgehide")
        If Page.IsPostBack Then
            dchide.Value = deptcode.Text
            'pnlSearch.Visible = False
            GridView1.Visible = True
        End If
    End Sub
    Protected Sub gvRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim drv As DataRowView = e.Row.DataItem
            Dim nameid As String = drv("empl_first").ToString & Space(5) & drv("empl_last").ToString & Space(5) & Space(5) & drv("employee_ID").ToString
            If tmpEmplID <> drv("employee_ID").ToString Then
                tmpEmplID = drv("employee_ID").ToString
                Dim tbl As Table = e.Row.Parent
                If Not IsDBNull(tbl) Then
                    Dim row As New GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal)
                    Dim cell As New TableCell
                    cell.ColumnSpan = Me.GridView1.Columns.Count

                    cell.Width = Unit.Percentage(100)
                    cell.Style.Add("font-weight", "bold")
                    cell.Style.Add("background-color", "#c0c0c0")
                    cell.Style.Add("color", "white")

                    row.Cells.Add(cell)

                    tbl.Rows.AddAt(tbl.Rows.Count - 1, row)

                    Session("tmpEmplID") = tmpEmplID
                End If

            End If

        End If

    End Sub
    Protected Sub GridView1_RowUpdated(ByVal sender As [Object], ByVal e As GridViewUpdatedEventArgs)

        ' Indicate whether the update operation succeeded. 
        If e.Exception Is Nothing Then
            Dim index As Integer = GridView1.EditIndex
            Dim row As GridViewRow = GridView1.Rows(index)
            'SendEmail(row.Cells(0).Text)
            btnSendEmail_Click()
            Message.Text = "Row updated successfully. Email Sent!"
        Else
            e.ExceptionHandled = True
            Message.Text = "An error occurred while attempting to update the row. No email sent."
        End If

    End Sub

    Protected Sub gridView_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
        tmpEmplID = ""
        GridView1.PageIndex = e.NewPageIndex
        GridView1.DataBind()
    End Sub

Open in new window

Why  there is bracket around object in below method? Please remove it.

Protected Sub GridView1_RowUpdated(ByVal sender As [Object], ByVal e As GridViewUpdatedEventArgs)

Ok, removed it.

Also added this ->System.Data.SqlClient like you suggesed.

Still no difference.
I am so  sleepy but I am very disparate.
http://www.java2s.com/Code/ASP/ADO.net-Database/CheckingforUpdateerrorsusingtheRowUpdatedeventC.htm Please refer this. This may help you.


 Did you debug the application? Have you found any exception in the GridView1_RowUpdated method?
ASKER CERTIFIED SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Hi CodeCruiser,

Thanks for the response.

I tried your suggestion. Still didn't work.

The weirdest thing is that it updates the first row but does not update any other row.

You have saved me before; hopefully you can do it again and I will be eternally grateful.
Sorry. By mistake I placed the link here. Please ignore above comment.
Remove DataFormatString="{0:c2}"  in your Gridview and check whethere update happens or not. The may be conversion problem while update data to database.
Nope, no love.

Unreal.

If I have to rewrite it, can you please suggest how?

It is becoming more and more like the option.

I have spent over a day on this.

The pressure is more intense given that it went live yesterday and they are clamoring for my head.

EaswaranP, I will take a look at the link.

What am I supposed to be looking at?

I hate to say this but I would use any help I can get to rewrite/fix.
EaswaranP, I just took a look at the post.

My issue is with updating rows one after the other but I don't see that on the link.

So, not sure what I am supposed to be looking at.
My biggest frustration is that as I look at the code sample, and a host of others I have looked at, I can't seem to see any difference between them and the one I posted above.

So, why is mine updating only the first row and nothing else?
Catch the rowupdating event and see what's going on by steping through it.
Funny thing is that at the end of the day, it is probably something very, very simple.

Right now though, I am just grabbing at straws.
I have been having a problem since yesterday and was pulling my remaining hair. Turned out that wrong types were assumed by svcutil when I updated my reference. So yes it may be a small thing but finding it out is a hard thing.
LOL, good a thing you still have some hair left.

Mine is gone, which is good because it would be weird looking gray at this time of my life.
OK, PROGRESS REPORT!!!!

I was able to perform my updates successfully, YEA.

BUT, now I am getting an error that "value cannot be null and it is pointing to my emai address which fires up email blast.

So, my question guys is, what role do these 2 subs below play. Evidently, my problem lies in them.

I removed them from my app and now i can update.

Can someone please tell me?

    Protected Sub gvOnDataBound2(ByVal sender As Object, ByVal e As System.EventArgs)
        SqlDataSource1.DataBind()
        Dim deptcode As Label = FormView1.FindControl("dept_codeLabel")
        Dim dchide As HiddenField = form1.FindControl("dchide")
        Dim pledgehide As HiddenField = form1.FindControl("pledgehide")
        If Page.IsPostBack Then
            dchide.Value = deptcode.Text
            'pnlSearch.Visible = False
            GridView1.Visible = True
        End If
    End Sub
    Protected Sub gvRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim drv As DataRowView = e.Row.DataItem
            Dim nameid As String = drv("empl_first").ToString & Space(5) & drv("empl_last").ToString & Space(5) & Space(5) & drv("employee_ID").ToString
            If tmpEmplID <> drv("employee_ID").ToString Then
                tmpEmplID = drv("employee_ID").ToString
                Dim tbl As Table = e.Row.Parent
                If Not IsDBNull(tbl) Then
                    Dim row As New GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal)
                    Dim cell As New TableCell
                    cell.ColumnSpan = Me.GridView1.Columns.Count

                    cell.Width = Unit.Percentage(100)
                    cell.Style.Add("font-weight", "bold")
                    cell.Style.Add("background-color", "#c0c0c0")
                    cell.Style.Add("color", "white")

                    row.Cells.Add(cell)

                    tbl.Rows.AddAt(tbl.Rows.Count - 1, row)

                    Session("tmpEmplID") = tmpEmplID
                End If

            End If

        End If

Open in new window

FINALLY, I *THINK*!!!!!!!

The problem is this line:

tbl.Rows.AddAt(tbl.Rows.Count - 1, row)

I commented it out and vavoom!

I am now able to update each row.

BUT, can you experts please take a look at that sub and advise of what that is supposed to do, PLEASE?
I still have an issue.

Since I commented this line:
tbl.Rows.AddAt(tbl.Rows.Count - 1, row)

out, when an email is sent now, it grabs the wrong person.

This remain an issue.
Guys, I am working really hard here to get this resolve and award points but I just need a little help from the experts.

From what I have been able to google up so far, my understanding is that because I am updating data via tbl.Rows.AddAt, I am only updating the grid HTML, not the database.

What I need to do to resolve this is to make changes to the underlying data source which is bound to the grid, and then perhaps re-databind the grid so that it sees the updated data source.

Sounds great but I need more seasoned .net experts to guide me.

Can you please help? I am in a serious bind.
Your code is adding rows to a table against each row in the Grid when the row is loaded from DB. Do you see any visual different when you comment out tbl.Rows.AddAt?
Yes, I just see each row being updated successfully and email sent out.

Problem, as stated, is that the email goes to the wrong person.

Based on what I have read so far, the solution is to do as I indicated in last post.

Unfortunately, I didn't see any sample code to get me going in the right direction.
How about using a SqlCommand and SqlConnection to do a Insert Into the backend DB? SqlDataSource does not provide a way of adding rows directly (to my knowledge).
Insert works fine.

I only have issues with the edit bit.
I still fail to understand the code in your RowDataBound event to be honest. Never seen something like this. Does it make any visual difference if you comment out that code? That code does not look like its related to email.
I still fail to understand the code in your RowDataBound event to be honest. Never seen something like this.

Open in new window


I totally agree with you 100%.

I stated, I think, at the outset that I didn't write it.

I would have done it differently.

This is why I am having such difficulty modifying it.

This is also one of the main reasons why I am not getting much help.

What I am focusing on now, is how to make the code update each row using gridview.

The only big worry right now is getting email sent to the right person.

If I didn't have to send emails, I would have removed the gvRowDataBound() sub completely.

We send emails based on employeeId and without that sub, I am having problem figuring out how to do it from either that selectcommand="... or from:

 <asp:Parameter Name="employee_ID" Type="String" />

or even from this:

                <asp:BoundField DataField="ID" HeaderText="ID" Visible = "false"
                    ReadOnly="True" SortExpression="ID" />

I am exploring every option available.

So, when I select updated records to be sent to the users, I can say something like:

where id = "&ID&" '--- this is from markup and ID is an integer datatype

or where employee_id = '"&employeeId&"' '--- from markup  and employee_id is string datatype
So the email is sent to everyone in the grid? You can try filling a datatable and sending email from there.
That's what I am doing.

The grid only has everything except employee names.

So, I query the database to grab the records that have been updated, along with the name of the employee who updated it, then send that employee an email based on employee id.

Since I wish to remove the gvRowDataBound() sub, I would like to figure out a way to compare the employeeid that Iam pulling from the db with the employeeid from the markup form.

Right now, I pull the employeeid from the db and assigned it a session variable.

I then use the session variable to compare with employeeid from the db.

This seems to update the records row by row - which is what I want but for some reason, the email doesn't go out anymore, sigh!
Can you show us that code? I may not be able to look at it till tomorrow (bed time).
I think I have been able to make it work.

The session approach appears to have worked.

I don't think I could have survived a whole day without coming up with a solution for this.

It is already live and it is highly visible.

I will do more testing tomorrow.
It's been quite awhile since I finally resolved this but I don't remember what I did to fix it.