<asp:DataGrid id="dgMain1" runat="server" ShowFooter="True" AllowPaging="True" AutoGenerateColumns="False" PageSize="20"> <Columns> <asp:ButtonColumn Text="详细" HeaderText="详细" CommandName="Select"></asp:ButtonColumn> <asp:BoundColumn DataField="MID" HeaderText="设备编号"></asp:BoundColumn> <asp:BoundColumn DataField="RepairCost" HeaderText="维修费用"></asp:BoundColumn> <asp:BoundColumn DataField="ManHour" HeaderText="工时"></asp:BoundColumn> <asp:BoundColumn DataField="num" HeaderText="维修次数"></asp:BoundColumn> </Columns> <PagerStyle Visible="False"></PagerStyle> </asp:DataGrid>
private double sum1 = 0; private double sum2 = 0; //注意Cells[n]里的值 private void dgMain1_ItemDataBound(object sender, DataGridItemEventArgs e) { if (WebUI.isDataItem(e.Item)) { e.Item.Cells[0].Attributes.Add("onclick", "setValue1('" + e.Item.Cells[1].Text + "');return false;");//点详细会弹出 //新页面, setValue1为JS里的函数 } if (e.Item.ItemIndex >= 0) { this.sum1 += double.Parse(WebUI.GetDGCellText(2, -1, e.Item)); this.sum2 += double.Parse(WebUI.GetDGCellText(3, -1, e.Item)); } else if (e.Item.ItemType == ListItemType.Footer)//添加总统计 { e.Item.Cells[0].Text = "总统计:"; e.Item.Cells[2].Text = this.sum1.ToString(); e.Item.Cells[3].Text = this.sum2.ToString(); } } } public class WebUI { /// <summary> /// 判断是否是GridView的项 /// </summary> /// <param name="dgi"></param> /// <returns></returns> public static bool isDataItem(DataGridItem dgi) { return ((dgi.ItemType == ListItemType.Item) || (dgi.ItemType == ListItemType.AlternatingItem)); } /// <summary> /// 返回GridView中单元格的值 /// </summary> /// <param name="CellIndex">GridView的列</param> /// <param name="ControlIndex">列中控件的位置,指示第几个控件</param> /// <param name="dgi"></param> /// <returns></returns> public static string GetDGCellText(int CellIndex, int ControlIndex, DataGridItem dgi) { if (ControlIndex == -1) { return HttpUtility.HtmlDecode(dgi.Cells[CellIndex].Text).Trim(); } return GetCtrlText(dgi.Cells[CellIndex].Controls[ControlIndex]).Trim(); } /// <summary> /// 根据传入的控件,返回控件的值 /// </summary> /// <param name="Control"></param> /// <returns></returns> private static string GetCtrlText(object Control) { switch (Control.GetType().ToString()) { case "System.Web.UI.WebControls.TextBox": return ((TextBox)Control).Text; case "System.Web.UI.WebControls.DropDownList": return ((DropDownList)Control).SelectedValue; case "System.Web.UI.WebControls.RadioButtonList": return ((RadioButtonList)Control).SelectedValue; case "System.Web.UI.WebControls.CheckBox": return Convert.ToString(((CheckBox)Control).Checked); } return null; } }