General view of ASP.Net grid General overview in Gridview
I have seen several tutorials on how to achieve this.
However, in my opinion, they require a lot of prior knowledge on how to programmatically access each element.
Does anyone have a link or can create a relatively basic example of how to achieve the grand total in the footer for ASP: Gridview?
a source to share
This is what I am using:
protected void InvoiceGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
var invoice = (Invoice) e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.Header)
{
totalAmt = 0;
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
totalAmt += invoice.Amount;
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
var amountTotalLabel = (TextBox) e.Row.FindControl("AmountTotalTextBox");
amountTotalLabel.Text = totalAmt.ToString("0.00");
}
}
TotalAmt is a protected instance variable on the page. Not sure if this is what you were looking for based on your comment about "programming knowledge". But it works and is pretty straight forward. In this case, the gridview is bound to List<Invoice>
.
a source to share
Add a footer template and on the RowDataBound, you have a global variable to store the sum of the summation,
In type e.Row.RowType = DataControlRowType.DataRow do the summation, and @ the.Row.RowType = DataControlRowType.Footer will store the share in the corresponding cell
for more info @ MSDN LINK
a source to share
I think the method I'm using is pretty straightforward and doesn't require programmatically accessing the columns in the Gridview, if that's what you mean. One of the nice parts is that after you get the functionality written down, you can add the totals to any Gridview just by editing the .aspx file.
In your GridView, make a column like this:
<asp:TemplateField HeaderText="Hours">
<ItemTemplate><%#DisplayAndAddToTotal(Eval("Hours").ToString(), "Hours")%></ItemTemplate>
<FooterTemplate><%#GetTotal("Hours")%></FooterTemplate>
</asp:TemplateField>
The second parameter DisplayAndAddToTotal can be whatever you want as long as you use the same string in GetTotal. I usually just use the field name. The two functions used are DisplayAndAddToTotal and GetTotal. They use a Hashtable to store totals so that they work on any number of columns you want to add. And they also work with counting the number "True" for a boolean field.
Protected total As Hashtable = New Hashtable()
Protected Function DisplayAndAddToTotal(itemStr As String, type As String) As Double
Dim item As Double
If itemStr = "True" Then
item = 1
ElseIf Not Double.TryParse(itemStr, item) Then
item = 0
End If
If total.ContainsKey(type) Then
total(type) = Double.Parse(total(type).ToString()) + item
Else
total(type) = item
End If
Return item
End Function
Protected Function GetTotal(type As String) As Double
Try
Dim result As Double = Double.Parse(total(type).ToString())
Return result
Catch
Return 0
End Try
End Function
a source to share