Trigger a GridView Update when a value needs to be changed programatically

megnin
megnin used Ask the Experts™
on
I have two GridViews in a Master/Detail arrangement.  It's a Purchase Requisition form where the main information is in GridVew1 and the Items are in GridView2.  On this page if you Select a Purchase Requisition record in GridView1 then GridView2 displays all the Items associated with that PR.

I'm trying to add a Button to VOID out a PR by setting the Quantity of all the Items to zero (0).  I started by having the button just update the Quantity field in the database setting it to zero, but that does not trigger GridView2 to update its subtotals and update the grand total in GridView1.

Just doing what I have so far does update the Quantity in GridView2, but leaves the subtotals unchanged.  If I click Edit and then Update (Save) on the Item in GridView2 it updates everything like it should.

I put GridView2.DataBind() at the end of the Void Button click event, but it doesn't trigger the Update that makes all the calculations happen, it just updates the one Quantity field.

Here is the current button click:
    Protected Sub btnVoid_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnVoid.Click
        Dim DBConn As New SqlConnection(ConfigurationManager.ConnectionStrings("PurchaseReqConnectionString").ConnectionString)
        Dim DBCmd As New SqlCommand
        Try
            Dim row As GridViewRow = Me.GridView1.SelectedRow
            Dim vReqID As Integer = row.Cells(1).Text

            Dim sql As String
            sql = "UPDATE Items SET Quantity = 0 WHERE ReqID = @ReqID"  'ItemID = @ItemID and ReqID = @ReqID"
            DBConn.Open()
            'Add UPDATE Statement 
            DBCmd = New SqlCommand(sql, DBConn)

            'Add Database Parameters
            DBCmd.Parameters.Add("@ReqID", SqlDbType.Int).Value = vReqID

            DBCmd.ExecuteNonQuery()

        Catch exp As Exception
            Response.Write(exp.Message)
            Label1.Text = exp.Message
        End Try
        'Close Database connection 
        DBCmd.Dispose()
        DBConn.Close()
        DBConn = Nothing

        GridView2.DataBind()
    End Sub

Open in new window


Here is GridView2:
	<asp:GridView ID="GridView2" runat="server" AllowSorting="True" AutoGenerateColumns="False" 
		CellPadding="4" DataKeyNames="ItemID" DataSourceID="SqlDataSource2" ForeColor="#333333" 
		ShowFooter="True">
		<RowStyle BackColor="#EFF3FB" />
		<Columns>
			<asp:CommandField ShowEditButton="True" UpdateText="Save" />
			<asp:BoundField DataField="ItemID" HeaderText="ItemID" InsertVisible="False" ReadOnly="True" 
				SortExpression="ItemID" Visible="False" />
			<asp:BoundField DataField="ItemNumber" HeaderText="Item #" SortExpression="ItemNumber" ReadOnly="true" >
			<ItemStyle HorizontalAlign="Center" />
			</asp:BoundField>
			<asp:BoundField DataField="ReqID" HeaderText="Requisition" SortExpression="ReqID" ReadOnly="true" >
			<ItemStyle HorizontalAlign="Center" />
			</asp:BoundField>
			<asp:BoundField DataField="Quantity" HeaderText="Qty" SortExpression="Quantity" >
			<ControlStyle Width="50px" />
			<ItemStyle HorizontalAlign="Right" Width="50px" />
			</asp:BoundField>
			<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
			<asp:BoundField DataField="UnitPrice" DataFormatString="{0:c}" HeaderText="Unit Price" ApplyFormatInEditMode="false"
				HtmlEncode="False" SortExpression="UnitPrice" >
			<ControlStyle Width="50px" />
			<ItemStyle HorizontalAlign="Right" Width="50px" />
			</asp:BoundField>
			<asp:BoundField DataField="SubTotal" DataFormatString="{0:c}" HeaderText="SubTotal" ReadOnly="true"
				HtmlEncode="False" SortExpression="SubTotal" >
			<ItemStyle HorizontalAlign="Right" />
			</asp:BoundField>
			<asp:BoundField DataField="ModifiedBy" HeaderText="Modified By" SortExpression="ModifiedBy" 
				ReadOnly="True" >
			<ItemStyle Wrap="False" />
			</asp:BoundField>
			<asp:BoundField DataField="DateModified" HeaderText="Date Modified" SortExpression="DateModified" 
				DataFormatString="{0:d}" HtmlEncode="False" ReadOnly="True" >
			<ItemStyle Wrap="False" HorizontalAlign="Right" />
			</asp:BoundField>
		</Columns>
		<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
		<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
		<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
		<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
		<EditRowStyle BackColor="#FF99FF" />
		<AlternatingRowStyle BackColor="White" />
	</asp:GridView>

Open in new window


I hope all I need to do is to somehow trigger GridView2 to do an Edit/Update cycle.  Thanks.
Oh, if it's relevant the number of items could be anything from 1 to 10.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2012
Top Expert 2014

Commented:
You need to call the Select method of SqlDataSource2 to force it to refresh its data before you call the DataBind on grid.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.select.aspx

Author

Commented:
I'm not sure if that the right example for me.  I'm using a GridView not a DataView.  I tried the code in that example anyway but when I get to
reorderedProducts = CType(dv.Table.Rows(0)(0), Integer)
In my code it's:
Items= CType(dv.Table.Rows(0)(0), Integer) (...and I've declared dv  As GridView)
I get 'Table is not a member of 'System.Web.UI.WebControls.Gridview'.
Most Valuable Expert 2012
Top Expert 2014

Commented:
Try adding

SqlDataSource2.Select(DataSourceSelectArguments.Empty)

before the Gridview2.DataBind()
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

Author

Commented:
The Quantities still go to zero but the subtotals still don't update like they do when I actually click on 'Edit' and then 'Update' in GridView2.

        End Try
        'Close Database connection 
        DBCmd.Dispose()
        DBConn.Close()
        DBConn = Nothing

        SqlDataSource2.Select(DataSourceSelectArguments.Empty)

        GridView2.DataBind()
        'GridView2.EditIndex = 0 <-- this puts Item #1 into Edit Mode and if I just click Update everything updates like it's supposed to, but it's commented out because it only affects one item.
    End Sub

Open in new window

Most Valuable Expert 2012
Top Expert 2014

Commented:
Show the code that is calculating the subtotals.

Author

Commented:

Protected Sub GridView2_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView2.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        ' add the UnitPrice and QuantityTotal to the running total variables
        priceTotal += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, _
          "SubTotal"))
        quantityTotal += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, _
          "Quantity"))
    ElseIf e.Row.RowType = DataControlRowType.Footer Then
        e.Row.Cells(0).Text = "Totals:"
        ' for the Footer, display the running totals
        e.Row.Cells(7).Text = priceTotal.ToString("c")
        e.Row.Cells(4).Text = quantityTotal.ToString("d")

        e.Row.Cells(7).HorizontalAlign = HorizontalAlign.Right
        e.Row.Cells(4).HorizontalAlign = HorizontalAlign.Right
        e.Row.Font.Bold = True

        ' Grab the ReqID from column 3 and total price.  Send them to Requisitions Table.
        iReqID = GridView1.SelectedValue 'CType(e.Row.Cells(3).TabIndex, Integer)

        ''I inserted the two lines below to update the total price field in the Requisitions table, but they execute too many time.  Should only fire once at the end.
        Call SendTotalToRequisition(priceTotal, iReqID)
        GridView1.DataBind()
    End If

End Sub

Open in new window

Most Valuable Expert 2012
Top Expert 2014

Commented:
Set a breakpoint and see if the event is firing at all.

Author

Commented:
I'm not having any luck debugging the page.  It keeps trying to open in UltraEdit, but I have the file association in Windows Explorer set to IE for .aspx files and no references to .aspx files in UE.  Kind of hampers me a bit. :-(
Most Valuable Expert 2012
Top Expert 2014

Commented:
When you have the solution open in VS, right click on the page in solution explorer and select "View in Browser"

Author

Commented:
Can I just:
Call GridView2_RowDataBound  ?

Author

Commented:
Okay.

Author

Commented:
It still tries to open in UE.  :-(

Author

Commented:
I tried Tools | Options | Restore File Associations in VS and that made no difference.
Most Valuable Expert 2012
Top Expert 2014

Commented:
Right click on file, goto open with, select "Choose...", chose IE and tick "Always open with this program"

Author

Commented:
Okay, sorry about that, I selected Browse With and was able to set IE back to the Default Browser.  Now I'll go set that breakpoint...

Author

Commented:
Yeah, it fired five times; once for each item in the PR I selected.  Quantity was set to 0 as desired but maybe because I'm putting the 0 directly into the database and not into the GridView it's updating the Quantity on the final DataBind after the RowDataBound event and done it's thing with no changes in the GridView yet.  ?
Most Valuable Expert 2012
Top Expert 2014

Commented:
The RowDataBound should be happening AFTER the changes have been made in the DB. It should be using the new values.

Author

Commented:
Just looking at the logic, it seems like it should work.
The button click is sticking 0 values into the Quantity field of any Item record that matches the selected Requisiton ID.  That's working.
Then SqlDataSource2.Select seems like it should be selecting the records from the database back into the GridView2 (I'm making assumptions here because I don't know the code that well.)
Then the GridView2.DataBind should trigger, and seems to be, the RowDataBound routine which calculates the subtotals.
Most Valuable Expert 2012
Top Expert 2014

Commented:
Yes the code should work logically.

You may want to try using a DataTable instead of SqlDataSource to populate the grid.

Author

Commented:
Ugh.  I was hopeing not to have to do a re-design of this thing.  I thought I'd add the "Void" button functionality real quick and move on to a more important project...

When I just stepped throught the code with a breakpoint on the GridView2.DataBind I saw that it was going through all the calculation steps in the RowDataBound BEFORE the 0 value was put into the GridView.  I'm going to try calling DataBind twice and see what happens.

Author

Commented:
That didn't change anything.  I tried clicking the "Void Button" twice and that didn't update the subtotals either even though the 0's were in the Quantity fields.  :-(

Author

Commented:
I think I'm just going to tell the users to click "Edit" and then "Update" on each row to "set" the 0 value that's put there by the "Void" button.

Author

Commented:
What if I took the code from the RowDataBound routine and put a copy of it into the Void Button and chanage it so that instead of calculating the existing Quantities it just inserted 0's and then did it's calculation? [Tell me if I'm just being stupid ;-) ]

Author

Commented:
Okay, I saw pretty quick that that was a dumb idea... ;-)
Most Valuable Expert 2012
Top Expert 2014

Commented:
You are setting quantities to 0 in void for the whole requisition right? Would the subtotals be not 0 as well then?

Author

Commented:
Right.  The purpuse of the button is to Void out an entire Requisition and set all the values to 0 so that it doesn't add to any "Totals" reports.  I thought I'd make the button set the quantities to 0 and everything else would calculate out to 0 automatically.  But the important thing is just to get the totals set to zero.  
Most Valuable Expert 2012
Top Expert 2014
Commented:
Can you not set the totals to 0 directly?

Author

Commented:
Yeah, I had just gone down this path and thought it might be an easy thing to trigger the update with just the 0s in the quantity field.  I may have to set all the sub totals in GridView2 as well as the "Grand Total" in GridView1 directly.

Author

Commented:
Thanks for the help.  I guess that's what I'll do.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial