先设置gridview的ShowFooter="True" ,每次gridview读取绑定数据都会出发gridview中的GridView1_RowDataBound事件,从而得到每一行的数据。
第一种情况。gridview动态绑定数据。
aspx
<
asp:GridView
ID
=
"GridView2"
runat
=
"server"
AutoGenerateColumns
=
"False"
OnRowDataBound
=
"GridView1_RowDataBound"
ShowFooter
=
"true"
>
<
Columns
>
<
asp:TemplateField
>
<
ItemTemplate
>
<
asp:Label
ID
=
"labelfirst"
runat
=
"server"
Text='<%# Eval("shuju")
%>'></
asp:Label
>//shuju为自己绑定数据库中
</
ItemTemplate
>
<
FooterTemplate
>
<
asp:Label
id
=
"labelAll"
runat
=
"server"
Text
=
"总计:"
></
asp:Label
>
</
FooterTemplate
>
</
asp:TemplateField
>
</
Columns
>
</
asp:GridView
>
cs中
private
int
num = 0;
protected
void
GridView1_RowDataBound(
object
sender, GridViewRowEventArgs e)
{
if
(e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView dr = e.Row.DataItem
as
DataRowView;
num += Convert.ToInt32(dr.Row[
"shuju"
]);//行标题
}
else
if
(e.Row.RowType == DataControlRowType.Footer)
{
Label LabelAll = e.Row.FindControl(
"labelAll"
)
as
Label;
if
(LabelAll !=
null
)
{
LabelAll.Text += num.ToString();
//"计算的总数,或者也可以单独计算";//
}
}
}
第二种情况grid没有绑定数据
aspx中
<asp:GridView
ShowFooter="True" ID="GridView2" runat="server" BackColor="White"
BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3"
ForeColor="Black" GridLines="Vertical" style="margin-left: 0px"
onrowdatabound="GridView2_RowDataBound" >
<AlternatingRowStyle BackColor="#CCCCCC" /> </asp:GridView>
cs中
double num = 0;
double i = 0;
double numfz = 0;
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView dr = e.Row.DataItem as DataRowView;
num += Convert.ToDouble(dr.Row["bidui"]);//数据库中有数据为12.3,则用ToDouble,比对为表列名称,获得其中内容
numfz += Convert.ToDouble(dr.Row["fuzhi"]);
i++;
}
else if (e.Row.RowType == DataControlRowType.Footer) //绑定到最后一行时候,RowType 为DataControlRowType.Footer
{
//Label LabelAll = e.Row.FindControl("labelAll") as Label;
//if (LabelAll != null)
//{
// LabelAll.Text += num.ToString();//"计算的总数,或者也可以单独计算";//
//}
e.Row.Cells[0].Text = "总计: "+i+"条"; //这是最后一行第一个单元格里面内容信息
e.Row.Cells[12].Text = "总计: " + num;
e.Row.Cells[13].Text = "总计: " + numfz ;
}
}