使用DATATGRID实现分组小计功能

此博客展示了用C#实现Web数据表格及汇总行功能的代码。包含ASPX页面的UI设计,如DataGrid表格、下拉列表等,以及C#代码逻辑,包括数据读取、存储、更新视图等操作,还对汇总行样式和文本进行了处理。



<%@ Page language="c#" Codebehind="WebForm6.aspx.cs" AutoEventWireup="false" Inherits="c4.WebForm6" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<title>Summary Rows</title>
<style>
HR { COLOR: black; HEIGHT: 2px }
.StdTextBox { BORDER-RIGHT: black 1px solid; BORDER-TOP: black 1px solid; FONT-SIZE: x-small; FILTER: progid:DXImageTransform.Microsoft.dropshadow(OffX=2, OffY=2, Color='gray', Positive='true'); BORDER-LEFT: black 1px solid; BORDER-BOTTOM: black 1px solid; FONT-FAMILY: verdana }
.StdText { FONT-SIZE: x-small; FONT-FAMILY: verdana }
</style>
<BODY bgcolor="ivory" style="FONT-SIZE:small;FONT-FAMILY:verdana">
<!-- ASP.NET Form -->
<form runat="server" ID="Form1">
<!-- Grid and the remainder of the page -->
<table>
<tr>
<td valign="top">
<asp:DataGrid id="grid" runat="server" AutoGenerateColumns="false" AllowPaging="true" PageSize="15"
Font-Size="xx-small" CellSpacing="0" CellPadding="4" DataKeyField="MyCustomerId" BorderStyle="solid"
BorderColor="skyblue" BorderWidth="1" GridLines="both">
<headerstyle backcolor="skyblue" font-size="9pt" font-bold="true" />
<itemstyle backcolor="#eeeeee" />
<pagerstyle backcolor="skyblue" font-name="webdings" font-size="10pt" PrevPageText="3" NextPageText="4" />
<Columns>
<asp:BoundColumn DataField="MyCustomerId" HeaderText="Customer" />
<asp:BoundColumn DataField="MyOrderId" HeaderText="Order #" />
<asp:BoundColumn DataField="price" HeaderText="Amount" DataFormatString="{0:c}">
<itemstyle horizontalalign="right" />
</asp:BoundColumn>
</Columns>
</asp:DataGrid>
</td>
<td valign="top" width="20"></td>
<td valign="top">
<b>Year</b>
<asp:dropdownlist runat="server" id="ddYears">
<asp:listitem runat="server" ID="Listitem1" NAME="Listitem1">1998</asp:listitem>
<asp:listitem runat="server" ID="Listitem2" NAME="Listitem2">1997</asp:listitem>
<asp:listitem runat="server" ID="Listitem3" NAME="Listitem3">1996</asp:listitem>
</asp:dropdownlist>
<asp:linkbutton runat="server" text="Load..." onclick="OnLoadYear" ID="Linkbutton1" NAME="Linkbutton1" />
<br>
<br>
<asp:label runat="server" cssclass="StdText" id="lblMsg" />
</td>
</tr>
</table>
<hr>
</form>
</BODY>
</HTML>



//cs代码
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Text;
namespace c4
{
/// <summary>
/// WebForm6 的摘要说明。
/// </summary>
public class WebForm6 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid grid;
protected System.Web.UI.WebControls.DropDownList ddYears;
protected System.Web.UI.WebControls.LinkButton Linkbutton1;
protected System.Web.UI.WebControls.Label lblMsg;

private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
// Load data and refresh the view
DataFromSourceToMemory("MyDataSet");
UpdateDataView();
}
}
// DataFromSourceToMemory
private void DataFromSourceToMemory(String strDataSessionName)
{
// Gets rows from the data source
DataSet oDS = PhysicalDataRead();

// Stores it in the session cache
Session[strDataSessionName] = oDS;
}

// PhysicalDataRead
private DataSet PhysicalDataRead()
{
String strCnn = "server=localhost;initial catalog=northwind;uid=sa;";
SqlConnection conn = new SqlConnection(strCnn);

// Command text using WITH ROLLUP
StringBuilder sb = new StringBuilder("");
sb.Append("SELECT ");
sb.Append(" CASE GROUPING(o.customerid) WHEN 0 THEN o.customerid ELSE '(Total)' END AS MyCustomerID, ");
sb.Append(" CASE GROUPING(od.orderid) WHEN 0 THEN od.orderid ELSE -1 END AS MyOrderID, ");
sb.Append(" SUM(od.quantity*od.unitprice) AS price ");
sb.Append("FROM Orders o, [Order Details] od ");
sb.Append("WHERE Year(orderdate) = @TheYear AND od.orderid=o.orderid ");
sb.Append("GROUP BY o.customerid, od.orderid WITH ROLLUP ");
sb.Append("ORDER BY o.customerid, price");
String strCmd = sb.ToString();
sb = null;

SqlCommand cmd = new SqlCommand();
cmd.CommandText = strCmd;
cmd.Connection = conn;

SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;

// Set the "year" parameter
SqlParameter p1 = new SqlParameter("@TheYear", SqlDbType.Int);
p1.Direction = ParameterDirection.Input;
p1.Value = Convert.ToInt32(ddYears.SelectedItem.Text);
cmd.Parameters.Add(p1);

// The DataSet contains two tables: Orders and Orders1.
// The latter is renamed to "OrdersSummary" and the two will be put into
// relation on the CustomerID field.
DataSet ds = new DataSet();
da.Fill(ds, "Orders");

return ds;
}
// Refresh the UI
private void UpdateDataView()
{
// Retrieves the data
DataSet ds = (DataSet) Session["MyDataSet"];
DataView dv = ds.Tables["Orders"].DefaultView;

// Re-bind data
grid.DataSource = dv;
grid.DataBind();
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.grid.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.grid_ItemCreated);
this.grid.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.grid_PageIndexChanged);
this.grid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.grid_ItemDataBound);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void grid_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Get the newly created item
ListItemType itemType = e.Item.ItemType;

///////////////////////////////////////////////////////////////////
// ITEM and ALTERNATINGITEM
if (itemType == ListItemType.Item || itemType == ListItemType.AlternatingItem)
{
DataRowView drv = (DataRowView) e.Item.DataItem;
if (drv != null)
{
// Check here the app-specific way to detect whether the
// current row is a summary row

if ((int) drv["MyOrderID"] == -1)
{
// Modify the row layout as needed. In this case,
// + change the background color to white
// + Group the first two cells and display company name and #orders
// + Display the total of orders
// Graphical manipulations can be done here. Manipulations that require
// data access should be done hooking ItemDataBound. They can be done
// in ItemCreated only for templated columns.
e.Item.BackColor = Color.White;
e.Item.Font.Bold = true;
e.Item.Cells.RemoveAt(1);// remove the order # cell
e.Item.Cells[0].ColumnSpan = 2;// span the custID cell
e.Item.Cells[1].HorizontalAlign = HorizontalAlign.Right;
}

}
}
}

private void grid_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
grid.CurrentPageIndex = e.NewPageIndex;
UpdateDataView();
}

private void grid_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Retrieve the data linked through the relation
// Given the structure of the data ONLY ONE row is retrieved
DataRowView drv = (DataRowView) e.Item.DataItem;
if (drv == null)
return;

// Check here the app-specific way to detect whether the
// current row is a summary row
if ((int) drv["MyOrderID"] == -1)
{
if (drv["MyCustomerID"].ToString() == "(Total)")
{
e.Item.BackColor = Color.Yellow;
e.Item.Cells[0].Text = "订单总计";
}
else
e.Item.Cells[0].Text = "客户小计:";
}
}
public void OnLoadYear(Object sender, EventArgs e)
{
DataFromSourceToMemory("MyDataSet");
UpdateDataView();
}
}
}

vb.net操作DataGridView控件的用法的集合,包括: 1. DataGridView当前的单元格属性取得、变更 2. DataGridView编辑属性 3. DataGridView最下面一列新追加行非表示 4. DataGridView判断当前选中行是否为新追加的行 5. DataGridView删除行可否设定 6. DataGridView行列不表示和删除 DataGridView控件用法合集(二) 7. DataGridView行列宽度高度设置为不能编辑 8. DataGridView行高列幅自动调整 9. DataGridView指定行列冻结 10. DataGridView列顺序变更可否设定 11. DataGridView行复数选择 12. DataGridView选择的行、列、单元格取得 DataGridView控件用法合集(三) 13. DataGridView指定单元格是否表示 14. DataGridView表头部单元格取得 15. DataGridView表头部单元格文字列设定 16. DataGridView选择的部分拷贝至剪贴板 17.DataGridView粘贴 18. DataGridView单元格上ToolTip表示设定(鼠标移动到相应单元格上时,弹出说明信息) DataGridView控件用法合集(四) 19. DataGridView中的ContextMenuStrip属性 20. DataGridView指定滚动框位置 21. DataGridView手动追加列 22. DataGridView全体分界线样式设置 23. DataGridView根据单元格属性更改显示内容 24. DataGridView新追加行的行高样式设置る 25. DataGridView新追加行单元格默认值设置 DataGridView中输入错误数据的处理(五) 26. DataGridView单元格数据错误标签表示 27. DataGridView单元格内输入值正确性判断 28. DataGridView单元格输入错误值事件的捕获 DataGridView控件用法合集(六) 29. DataGridView行排序(点击列表头自动排序的设置) 30. DataGridView自动行排序(新追加值也会自动排序) 31. DataGridView自动行排序禁止情况下的排序 32. DataGridView指定列指定排序 DataGridView控件用法合集(七) 33. DataGridView单元格样式设置 34. DataGridView文字表示位置的设定 35. DataGridView单元格内文字列换行 36. DataGridView单元格DBNull值表示的设定 37. DataGridView单元格样式格式化 38. DataGridView指定单元格颜色设定 39. DataGridView单元格文字字体设置 40. DataGridView根据单元格值设定单元格样式 DataGridView控件用法合集(八) 41. DataGridView设置单元格背景颜色 42. DataGridView行样式描画 43. DataGridView显示行号 44. DataGridView焦点所在单元格焦点框不显示的设定 DataGridView控件用法合集(九) 45. DataGridView中显示选择框CheckBox 46. DataGridView中显示下拉框ComboBox 47. DataGridView单击打开下拉框 48. DataGridView中显示按钮 49. DataGridView中显示链接 50. DataGridView中显示图像 DataGridView控件用法合集(十) 51. DataGridView编辑中单元格控件取得 52. DataGridView输入自动完成 53. DataGridView单元格编辑时键盘KEY事件取得 54. DataGridView下拉框(ComboBox)单元格编辑时事件取得 55. DataGridView下拉框(ComboBox)单元格允许文字输入设定 DataGridView控件用法合集(十一) 56. DataGridView根据值不同在另一列中显示相应图片 57. DataGridView中显示进度条(ProgressBar) 58. DataGridView中添加MaskedTextBox DataGridView控件用法合集(十二) 59. DataGridView中Enter键按下焦点移至旁边的单元格 60. DataGridView行集合化(Group)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值