trying to total gridview in asp - asp.net

i am trying to total the price and quantity of all the products added to the gridview and i can't seem to figure out why the total is not showing in the footer. the code that i have for the vb should multiply the quantity with the price and put it into the footer of the gridview. the gridview footer is visible so i know that's not the problem. any help would be appreciated.
asp:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="Cart" AllowSorting="True" BackColor="White"
BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
GridLines="Vertical" ShowFooter="True" AutoGenerateEditButton="True"
AutoGenerateDeleteButton="True" DataKeyNames="cartID">
<AlternatingRowStyle BackColor="Gainsboro" />
<Columns>
<asp:BoundField DataField="cartID" HeaderText="cartID" SortExpression="cartID"
InsertVisible="False" ReadOnly="True" Visible="False"></asp:BoundField>
<asp:BoundField DataField="cartNO" HeaderText="cartNO" SortExpression="cartNO"
Visible="False" />
<asp:BoundField DataField="productID" HeaderText="productID"
SortExpression="productID" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="productName" HeaderText="productName"
SortExpression="productName" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="price" HeaderText="price"
SortExpression="price" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="quantity" HeaderText="quantity"
SortExpression="quantity" />
<asp:TemplateField HeaderText="SubTotal" SortExpression="subTotal" >
<ItemTemplate>
<%# Eval("price") * Eval("quantity")%>
</ItemTemplate>
<%-- <FooterTemplate>
<asp:Label ID="sum" runat="server"/>
</FooterTemplate>--%>
</asp:TemplateField>
VB
Public Class MyCart
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strcartNO As String = ""
Dim cookieBack As HttpCookie
cookieBack = HttpContext.Current.Request.Cookies("cartNO")
strcartNO = cookieBack.Value
'sqldscartLine.selectCommand = "Select * from cartLine where cartNO = '" & strcartNO & "'"
GridView1.DataBind()
End Sub
Public Shared Sub DeleteMethod(ByVal original_OrderID As Integer, _
ByVal original_ProductID As Integer)
End Sub
Dim priceTotal As Decimal = 0
Dim quantityTotal As Integer = 0
Sub GridView1_RowDataBound(ByVal sender As Object, _
ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
' add the UnitPrice and QuantityTotal to the running total variables
priceTotal += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, _
"price"))
quantityTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"quantity"))
ElseIf e.Row.RowType = DataControlRowType.Footer Then
e.Row.Cells(2).Text = "Totals:"
' for the Footer, display the running totals
e.Row.Cells(3).Text = priceTotal.ToString("c")
e.Row.Cells(4).Text = quantityTotal.ToString("d")
e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right
e.Row.Cells(4).HorizontalAlign = HorizontalAlign.Right
e.Row.Font.Bold = True
End If
End Sub

Not sure if anybody saw the comment, so will put it in an answer instead - This might help others out (if I'm correct..)
Your code has the following in
<%-- <FooterTemplate>
<asp:Label ID="sum" runat="server"/>
</FooterTemplate>--%>
The <%-- and --%> are comments, so your footer is being commented out.
Change it to
<FooterTemplate>
<asp:Label ID="sum" runat="server"/>
</FooterTemplate>
And it should display.

Databinding creates data rows. The footer isn't a data row, so the event RowDataBound is not called when it's created. Thus, your event handler GridView1_RowDataBound will never execute the code that generates the totals, since the expression
e.Row.RowType = DataControlRowType.Footer
... will never be true during any execution of that method.
Try handling the RowCreated event instead, like so:
Sub GridView1_RowCreated(ByVal sender As Object, _
ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.Footer Then
e.Row.Cells(2).Text = "Totals:"
' for the Footer, display the running totals
e.Row.Cells(3).Text = priceTotal.ToString("c")
e.Row.Cells(4).Text = quantityTotal.ToString("d")
e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right
e.Row.Cells(4).HorizontalAlign = HorizontalAlign.Right
e.Row.Font.Bold = True
End If
End Sub

Related

Adding Dropdown List Item to ASP GridView

I want to be able to take a selected item from a dropdown list, hit a button, and have that item added to a GridView to be viewed by the user. Right now, when I hit the + button, the grid displays, but the cells are blank. Any suggestions?
ASP code:
<tr>
<td valign="top" colspan="2">
<b>Agents Visited</b><br />
<asp:DropDownList SelectionMode="Multiple" runat="server" ID="agentsDropdown" Name="agentsDropdown" width="425"></asp:DropDownList>
</td>
<td valign="top">
<br />
<asp:Button id="agentButton" name="agentButton" runat="server" Text="+" OnClick="AddAgent" CssClass="buttonstyle" onmouseover="shade(this);" onmouseout="unshade(this);" />
</td>
</tr>
<tr>
<asp:GridView ID="agentGridView" Visible="False" AllowSorting="False" AllowPaging="False" Runat="server" AutoGenerateColumns="False" PageSize="20" >
<Columns>
<asp:TemplateField HeaderText="Agent">
<ItemTemplate>
<asp:Label ID="agentName" runat="server" Text=''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:Label ID="agentValue" runat="server" Text=''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
</tr>
Initial GridView bind:
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack
agentGridView.DataSource = Nothing
agentGridView.Databind()
End If
End Sub
Additional code behind:
Protected Sub AddAgent(sender As Object, e As EventArgs)
If agentsDropdown.SelectedIndex > 0 Then
Dim dt As New DataTable
dt.Columns.Add("agentName")
dt.Columns.Add("agentValue")
Dim row1 As DataRow = dt.NewRow
row1.Item("agentName") = agentsDropdown.SelectedItem.Text.ToString()
row1.Item("agentValue") = agentsDropdown.SelectedValue.ToString()
dt.Rows.Add(row1)
agentGridView.DataSource = dt
agentGridView.DataBind()
agentsDropdown.SelectedIndex = 0
Dim agentRowsCount as Integer = agentGridView.Rows.Count
If agentRowsCount > 0
agentGridView.Visible = True
End If
End If
End Sub
This should work for you now. Change your GridView to the following:
<asp:GridView ID="agentGridView" Visible="False" AllowSorting="False" AllowPaging="False" Runat="server" AutoGenerateColumns="False" PageSize="20" >
<Columns>
<asp:BoundField DataField="agentName" HeaderText="Agent Name" ItemStyle-Width="30" />
<asp:BoundField DataField="agentValue" HeaderText="Agent Value" ItemStyle-Width="30" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
See if this will work for you. I am more c# however this looked like it worked:
Public Class WebForm1
Inherits System.Web.UI.Page
Dim dt = Nothing
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Session("Agents") Is Nothing) Then
dt = New DataTable
Else
dt = Session("Agents")
End If
If Not Page.IsPostBack Then
agentGridView.DataSource = Nothing
agentGridView.DataBind()
End If
End Sub
Protected Sub AddAgent(sender As Object, e As EventArgs) Handles agentsDropdown.SelectedIndexChanged
If agentsDropdown.SelectedIndex > 0 Then
If (Session("Agents") Is Nothing) Then
dt = New DataTable()
dt.Columns.Add("agentName")
dt.Columns.Add("agentValue")
End If
Dim row1 As DataRow = dt.NewRow
row1.Item("agentName") = agentsDropdown.SelectedItem.Text.ToString()
row1.Item("agentValue") = agentsDropdown.SelectedValue.ToString()
dt.Rows.Add(row1)
Session("Agents") = dt
agentGridView.DataSource = dt
agentGridView.DataBind()
agentsDropdown.SelectedIndex = 0
Dim agentRowsCount As Integer = agentGridView.Rows.Count
If agentRowsCount > 0 Then
agentGridView.Visible = True
End If
End If
End Sub
End Class

Multiple delete wont work (asp.net vb)

code sample aspx vb behind code:
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
For Each row As GridViewRow In GridView1.Rows
Dim checkbox As CheckBox = CType(row.FindControl("chkdelete"), CheckBox)
If checkbox.Checked Then
Dim ID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)
SqlDataSource1.DeleteParameters("ID").DefaultValue = ID.ToString()
SqlDataSource1.Delete()
End If
Next row
front code :
`
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkdelete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="No"
SortExpression="ID"/>
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name"/>
<asp:CommandField Headertext="Edit" ShowEditButton="True" />
<asp:CommandField Headertext="Delete" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:Button ID="btnDelete" runat="server" Text="Delete" onclick="btnDelete_Click"/>`
my question is, why my multiple delete still wont work? whats wrong with my code? anyone pls help..
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
For Each row As GridViewRow In GridView1.Rows
Dim checkbox As CheckBox = CType(row.FindControl("chkdelete"), CheckBox)
If checkbox.Checked Then
Dim ID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)
Delete(ID)
End If
Next row
End Sub
Public Function Delete(ByRef ID as Integer)
' Your Connection Coding comes here
SqlDataSource1.DeleteParameters("ID").DefaultValue = ID.ToString()
SqlDataSource1.Delete()
End Function
Try This Way..!!

GridView Edit Button Requires 2 Clicks

When pressing edit button in gridview, edit template is displayed only after 2 clicks.
And another problem: Value of the field to edit is displayed in gridview initially, but not in edit template.
Asp code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" CellPadding="4" OnRowEditing="EditRow"
OnRowCancelingEdit="CancelEditRow" DataKeyNames="AREA" DataMember="DefaultView">
<Columns>
<asp:BoundField DataField="AREA" HeaderText="AREA" ReadOnly="True"
SortExpression="AREA" />
<asp:TemplateField HeaderText="LEADER_USER" SortExpression="LEADER_USER">
<ItemTemplate><%#Eval("leader_user")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtleaderuser" runat="server" Text='<%#Eval("leader_user")%>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="editButton" runat="server" CommandName="Edit"
ImageUrl="images/pencil1.png" Text="Edit" ToolTip="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="BtnUpdate" runat="server" CommandName="Update"
Text="Update" />
<asp:Button ID="BtnCancel" runat="server" CommandName="Cancel"
Text="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
vb code:
Protected Sub EditRow(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
GridView1.DataSource = SqlDataSource1
'If Not IsPostBack Then
'GridView1.DataSourceID = SqlDataSource1.ID
'GridView1.DataBind()
'End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SqlDataSource1.SelectCommand = "SQL"
SqlDataSource1.ConnectionString = "My conn string"
If Not IsPostBack Then
'GridView1.DataSourceID = SqlDataSource1.ID
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
End If
End Sub
I think you need to call DataBind to rebind the data source. You've commented it out, but it looks like you had it in a IsPostBack block, which would only execute on the initial page load.
Try:
Protected Sub EditRow(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
End Sub

Sub routine for OnClick procedure in GridView is not executing

We have a GridView with a 2 buttons. One of the buttons is a select button and the other is a one without a command. It is supposed to activate an OnClick sub routine. The sub routine is not executing.
Here is the markup of the GridView with the buttons:
<asp:GridView
ID="GridViewParentsSummary"
runat="server"
AllowPaging="True"
AllowSorting="True"
AutoGenerateColumns="False"
DataKeyNames="ID"
>
<Columns>
<asp:BoundField
DataField="ID"
HeaderText="ID"
SortExpression="ID" InsertVisible="False" ReadOnly="True" Visible="False" />
<asp:BoundField
DataField="FatherName"
HeaderText="FatherName"
SortExpression="FatherName" />
<asp:BoundField DataField="MotherName" HeaderText="MotherName"
SortExpression="MotherName" />
<asp:ButtonField
ButtonType="Button"
CommandName="Select"
Text="Select Details" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button
ID="ButtonNewPersonToReleaseChildren"
runat="server"
CausesValidation="false"
Text="New Person To Release Children"
CommandArgument='<%# Eval("ID") %>'
OnClick="NewPersonToReleaseChildren" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the VB.Net code-behind coding with the sub routines for the buttons:
Protected Sub GridViewParentsSummary_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridViewParentsSummary.SelectedIndexChanged
IntParentsID = GridViewParentsSummary.DataKeys(GridViewParentsSummary.SelectedIndex).Value
Response.Redirect("AuthorizationForChildReleaseDetails.aspx")
End Sub
Protected Sub NewPersonToReleaseChildren(sender As Object, e As EventArgs)
blnAddModeIsSelected = True
MsgBox("The button was clicked.")
Response.Redirect("AuthorizationForChildReleaseDetails.aspx")
End Sub
I'm sure I am missing some coding but don't know what that could be because the sub routine for the Select button works, but not the sub routine for NewPersonToReleaseChildren.
in gridview:
<asp:TemplateField HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="ImgBtnDel" runat="server" ImageUrl="~/Images/icon-delete.gif" CommandName="del"
CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
use aspButton or Imagebutton in gridview,in code behind:
Protected Sub gridview1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridview1.RowCommand
Dim myId As String = e.CommandArgument.ToString
If e.CommandName = "del" Then
ElseIf e.CommandName = "upd" Then
End If
End Sub
Add Handles Handles NewPersonToReleaseChildren.Click to your handler
Protected Sub NewPersonToReleaseChildren(sender As Object, e As EventArgs) Handles NewPersonToReleaseChildren.Click
blnAddModeIsSelected = True
//MsgBox("The button was clicked.")
Response.Redirect("AuthorizationForChildReleaseDetails.aspx")
End Sub
I don't think there is anything like MsgBox in asp.net. If the Handles does not work, replace that line with Throw New Exception("My Button was called") or put a break point on that line and press F5

using IIf in a gridview control

I am trying to change the image url of an image control based on condition inside gridview below is my markup:
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# IIf(CDate(Eval("startdate")) < CDate(Eval("expdate")),"~/iWebmallManager/Images/bullet_red.png",
"~/iWebmallManager/Images/bullet_green.png" %>'
/>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
The IIf statement didn't work. i dont know what I am doing right please help
You should do that in codebehind, since it increases the readability and is easier to debug:
Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim rowView = DirectCast(e.Row.DataItem,DataRowView)
Dim Image1 = DirectCast(e.Row.FindControl("Image1"),Image)
Dim startdate = DirectCast(rowView("startdate"), Date)
Dim expdate = DirectCast(rowView("expdate"), Date)
If startDate < expdate
Image1.ImageUrl = "~/iWebmallManager/Images/bullet_red.png"
Else
Image1.ImageUrl = "~/iWebmallManager/Images/bullet_green.png"
End If
End If
End Sub

Resources