【发布时间】:2009-05-10 19:38:26
【问题描述】:
我已经看过几个关于如何实现这一点的教程。
但是,在我看来,他们需要大量有关如何以编程方式引用每个项目的先验知识。
是否有人有链接或可以创建一个相对基本的示例来说明如何在 ASP:Gridview 的页脚中获得运行总计?
【问题讨论】:
我已经看过几个关于如何实现这一点的教程。
但是,在我看来,他们需要大量有关如何以编程方式引用每个项目的先验知识。
是否有人有链接或可以创建一个相对基本的示例来说明如何在 ASP:Gridview 的页脚中获得运行总计?
【问题讨论】:
这是我用的:
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 是页面上受保护的实例变量。根据您对“程序化知识”的评论,不确定这是否是您要查找的内容。但它有效并且相当简单。在这种情况下,gridview 绑定到 List<Invoice>。
【讨论】:
添加footer Template并在RowDataBound上,有一个全局变量来存储总和,
在 e.Row.RowType = DataControlRowType.DataRow 类型处进行求和,@e.Row.RowType = DataControlRowType.Footer 将值存储在相应的单元格中
更多信息请看@MSDN LINK
【讨论】:
这就是我的做法。好简单。您只需将包含您的数字的行求和并将其放在页脚中。
((Label)GridView.FooterRow.Cells[1].FindControl("your_label")).Text = ds.Tables[0].Compute("sum(Column_name)", "").ToString();
【讨论】:
我认为我使用的方法非常基本,不需要以编程方式引用 Gridview 中的列,如果这就是您的意思的话。这是一个很好的部分,一旦你编写了后端函数,你只需编辑 .aspx 文件就可以将总计添加到任何 Gridview。
在您的 GridView 中,使列如下所示:
<asp:TemplateField HeaderText="Hours">
<ItemTemplate><%#DisplayAndAddToTotal(Eval("Hours").ToString(), "Hours")%></ItemTemplate>
<FooterTemplate><%#GetTotal("Hours")%></FooterTemplate>
</asp:TemplateField>
DisplayAndAddToTotal 的第二个参数可以是您想要的任何字符串,只要您在 GetTotal 中使用相同的字符串即可。我通常只是再次使用字段名称。这是使用的两个函数,DisplayAndAddToTotal 和 GetTotal。他们使用 Hashtable 来存储总数,以便它与您想要添加的任意数量的列一起使用。他们还可以计算布尔字段中“真”的数量。
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
【讨论】: