问题
I have this GridView, and I want to add in the footer summation of PremiseScore score (third column).
How I can do this?
<asp:BoundField DataField="PremiseUno" HeaderText='<%$ Resources:Language, grdPremiseUno %>' ReadOnly="True" SortExpression="PremiseUno" >
<HeaderStyle CssClass="gHeaderStyle" />
<ItemStyle CssClass="gControlStyle" />
</asp:BoundField>
<asp:BoundField DataField="PremiseName" HeaderText='<%$ Resources:Language, grdPremisesName %>'
ReadOnly="True" SortExpression="grdPremisesName" >
<HeaderStyle CssClass="gHeaderStyle" />
<ItemStyle CssClass="gControlStyle" />
</asp:BoundField>
<asp:BoundField DataField="PremiseScore" HeaderText='<%$ Resources:Language, grdPremiseScore %>' ReadOnly="True" SortExpression="PremiseScore" >
<HeaderStyle CssClass="gHeaderStyle" />
<ItemStyle CssClass="gControlStyle" />
</asp:BoundField>
<asp:TemplateField ShowHeader="False" HeaderText= '<%$ Resources:Language, btnDelete %>'>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" CommandArgument='<%# Eval("PremiseUno") %>' onclick="LinkButton1_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
回答1:
If you convert the bound field to a template field, you can access the control holding the value of premise score:
<asp:TemplateField HeaderText="test">
<ItemTemplate>
<asp:Label runat="server" ID="testLabel" Text='<%# Eval("PremiseScore") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
You can then do the following to compute the sum in the Databound-event of the gridview:
protected void Grid_DataBound(Object sender, EventArgs e)
{
GridViewRow footerRow = grid.FooterRow;
var sum = (from GridViewRow row in grid.Rows select ((Label)row.FindControl("testLabel")).Text).Sum(d => Convert.ToInt16(d));
footerRow.Cells[0].Text = sum.ToString();
}
I assume here that all values are ints, but it´s easily convertible to other value types.
来源:https://stackoverflow.com/questions/9602972/add-summary-row-in-gridview-for-one-column