Avatar of David Megnin
David MegninFlag for United States of America

asked on 

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

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.
ASP.NETVisual Basic.NET.NET Programming

Avatar of undefined
Last Comment
David Megnin
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

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
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

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'.
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Try adding

SqlDataSource2.Select(DataSourceSelectArguments.Empty)

before the Gridview2.DataBind()
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

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

Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Show the code that is calculating the subtotals.
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER


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

Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Set a breakpoint and see if the event is firing at all.
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

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. :-(
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

When you have the solution open in VS, right click on the page in solution explorer and select "View in Browser"
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

Can I just:
Call GridView2_RowDataBound  ?
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

Okay.
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

It still tries to open in UE.  :-(
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

I tried Tools | Options | Restore File Associations in VS and that made no difference.
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Right click on file, goto open with, select "Choose...", chose IE and tick "Always open with this program"
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

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...
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

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.  ?
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

The RowDataBound should be happening AFTER the changes have been made in the DB. It should be using the new values.
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

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.
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Yes the code should work logically.

You may want to try using a DataTable instead of SqlDataSource to populate the grid.
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

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.
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

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.  :-(
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

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.
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

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 ;-) ]
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

Okay, I saw pretty quick that that was a dumb idea... ;-)
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

You are setting quantities to 0 in void for the whole requisition right? Would the subtotals be not 0 as well then?
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

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.  
ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

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.
Avatar of David Megnin
David Megnin
Flag of United States of America image

ASKER

Thanks for the help.  I guess that's what I'll do.
.NET Programming
.NET Programming

The .NET Framework is not specific to any one programming language; rather, it includes a library of functions that allows developers to rapidly build applications. Several supported languages include C#, VB.NET, C++ or ASP.NET.

137K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo