转自:http://blog.csdn.net/net_lover/article/details/6692093
完全的源代码如下
- <%@ Page Language="C#" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <script runat="server">
- protected void Page_Load(object sender, EventArgs e)
- {
- System.Data.DataTable dataTable1 = new System.Data.DataTable("BlogUser");
- System.Data.DataRow dr;
- dataTable1.Columns.Add(new System.Data.DataColumn("Type", typeof(System.String)));
- dataTable1.Columns.Add(new System.Data.DataColumn("Count1", typeof(System.Int32)));
- dataTable1.Columns.Add(new System.Data.DataColumn("Count2", typeof(System.Int32)));
- Random r = new Random();
- for (int i = 0; i < 8; i++)
- {
- dr = dataTable1.NewRow();
- if (i < 8) dr[0] = "C";
- if (i < 6) dr[0] = "B";
- if (i < 3) dr[0] = "A";
- dr[1] = r.Next(0, 100);
- dr[2] = r.Next(0, 100);
- dataTable1.Rows.Add(dr);
- }
- System.Data.DataView dv = dataTable1.DefaultView;
- System.Data.DataTable dataTable2 = dv.ToTable(true, "Type");
- System.Data.DataTable dataTable3 = dataTable1.Clone();
- int totalCount1 = 0, totalCount2 = 0;
- for (int i = 0; i < dataTable2.Rows.Count; i++)
- {
- String type = dataTable2.Rows[i][0].ToString();
- System.Data.DataRow[] rs = dataTable1.Select("Type='" + type + "'");
- int count1 = 0, count2 = 0;
- for (int j = 0; j < rs.Length; j++)
- {
- count1 += Convert.ToInt32(rs[j]["Count1"]);
- count2 += Convert.ToInt32(rs[j]["Count2"]);
- dataTable3.ImportRow(rs[j]);
- }
- dr = dataTable3.NewRow();
- dr[0] = "合计";
- dr[1] = count1;
- dr[2] = count2;
- totalCount1 += count1;
- totalCount2 += count2;
- dataTable3.Rows.Add(dr);
- }
- dr = dataTable3.NewRow();
- dr[0] = "总合计";
- dr[1] = totalCount1;
- dr[2] = totalCount2;
- dataTable3.Rows.Add(dr);
- this.GridView1.DataSource = dataTable3;
- this.GridView1.DataBind();
- }
- protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- if (e.Row.Cells[0].Text.Trim().Equals("合计"))
- {
- e.Row.Style.Add("color", "#d00");
- }
- else if (e.Row.Cells[0].Text.Trim().Equals("总合计"))
- {
- e.Row.Style.Add("color", "#00d");
- e.Row.Style.Add("background", "#f33");
- }
- }
- </script>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
- </asp:GridView>
- </form>
- </body>
- </html>
运行效果