关闭

给DataGridView添加底部合计行的一种方法

744人阅读 评论(0) 收藏 举报

DataGridView是使用很多的控件,可是却没有底部合计行的功能,在做一个小项目时有很多地方要用到,就通过下面的方法实现了这一功能:

把下面  

 #region 添加DataGridView底行合计数 的四个方法  
和  
#endregion  添加DataGridView底行合计数 的四个方法
之间的 代码拷贝到你的程序中

然后再 给要计算合计的 DataGridView 对象(此处假定为dataGridView1) 绑定 下面的方法及 数据表  则可:

这里假设通过点击 按钮 之后 绑定

private void button1_Click(object sender, EventArgs e)
  {

     dataGridView1.DataSourceChanged += new EventHandler(dataGridView_DataSourceChanged);
   dataGridView1.ColumnHeaderMouseClick += new DataGridViewCellMouseEventHandler(dataGridView_ColumnHeaderMouseClick);
   dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView_CellValueChanged);
   dataGridView1.AllowUserToAddRows = false;
   dataGridView1.DataSource = 这里是要绑定的数据表;

  }

 

#region 添加DataGridView底行合计数 的四个方法
  /// <summary>
  /// 计算合计算
  /// </summary>
  /// <param name="dgv">要计算的DataGridView</param>
  private void SumDataGridView(DataGridView dgv)
  {

   #region 计算合计数
   //DataGridView dgv = (DataGridView)sender;
   if (dgv.DataSource == null) return;
   DataTable dt = (DataTable)dgv.DataSource;
   if (dt.Rows.Count < 1) return;
   decimal[] tal = new decimal[dt.Columns.Count];

   DataRow ndr = dt.NewRow();

   string talc = "";

   int number = 1;
   foreach (DataRow dr in dt.Rows)
   {
    dr["@xu.Hao"] = number++;
    int n = 0;
    foreach (DataColumn dc in dt.Columns)
    {


     if (talc == "" && dc.DataType.Name.ToUpper().IndexOf("STRING") >= 0) talc = dc.ColumnName;


     if (dc.DataType.IsValueType)
     {
      string hej = dr[dc.ColumnName].ToString();
      try
      {
       if (hej != string.Empty) tal[n] += decimal.Parse(hej);
      }
      catch (Exception) { }
      //if (hej != string.Empty) tal[n] += decimal.Parse(hej);
     }


     n++;
    }
   }

   ndr.BeginEdit();
   for (int i = 0; i < dt.Columns.Count; i++)
   {
    if (tal[i] != 0)
     ndr[i] = tal[i];
   }
   ndr["@xu.Hao"] = ((int)(dt.Rows.Count + 1)).ToString();
   if (talc != "") ndr[talc] = "[合计]";
   ndr.EndEdit();
   dt.Rows.Add(ndr);

   dgv.Rows[dgv.Rows.Count - 1].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 210);


   if (dgv.Tag == null)
   {
    foreach (DataGridViewColumn dgvc in dgv.Columns)
    {
     dgvc.SortMode = DataGridViewColumnSortMode.Programmatic;
    }
   }


   dgv.Tag = ndr;

   #endregion


  }
  private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
  {//
   //直接拷贝代码

   DataGridView sortDgv = (DataGridView)sender;
   int fx = 0;
   if (sortDgv.AccessibleDescription == null)
   {
    fx = 1;
   }
   else
   {
    fx = int.Parse(sortDgv.AccessibleDescription);
    fx = (fx == 0 ? 1 : 0);
   }
   sortDgv.AccessibleDescription = fx.ToString();
   if (sortDgv.Columns[e.ColumnIndex].Name == "@xu.Hao") return;
   DataGridViewColumn nCol = sortDgv.Columns[e.ColumnIndex];

   if (nCol.DataPropertyName == string.Empty) return;

   if (nCol != null)
   {
    sortDgv.Sort(nCol, fx == 0 ? ListSortDirection.Ascending : ListSortDirection.Descending);

   }
   //--
   DataRow dr = (DataRow)sortDgv.Tag;
   DataTable dt = (DataTable)sortDgv.DataSource;
   DataRow ndr = dt.NewRow();
   ndr.BeginEdit();
   for (int i = 0; i < dt.Columns.Count; i++)
   {
    ndr[i] = dr[i];
   }
   dt.Rows.Remove(dr);


   //if (e.ColumnIndex != 0)
   {
    int n = 1;
    for (int i = 0; i < sortDgv.Rows.Count; i++)
    {
     DataGridViewRow dgRow = sortDgv.Rows[i];
     DataRowView drv = (DataRowView)dgRow.DataBoundItem;
     DataRow tdr = drv.Row;
     tdr.BeginEdit();
     tdr["@xu.Hao"] = n;
     n++;
     tdr.EndEdit();

    }
    sortDgv.Refresh();
    sortDgv.RefreshEdit();

   }
   ndr["@xu.Hao"] = ((int)(dt.Rows.Count + 1)).ToString();
   ndr.EndEdit();
   dt.Rows.Add(ndr);
   sortDgv.Tag = ndr;

   //--
   sortDgv.Sort(sortDgv.Columns["@xu.Hao"], ListSortDirection.Ascending);
   sortDgv.Columns["@xu.Hao"].HeaderCell.SortGlyphDirection = SortOrder.None;
   nCol.HeaderCell.SortGlyphDirection = fx == 0 ? SortOrder.Ascending : SortOrder.Descending;
   sortDgv.Rows[sortDgv.Rows.Count - 1].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 210);

  }
  private void dataGridView_DataSourceChanged(object sender, EventArgs e)
  {
   DataGridView dgv = (DataGridView)sender;
   DataTable dt = (DataTable)dgv.DataSource;
   if (dt == null) return;
   decimal[] tal = new decimal[dt.Columns.Count];
   if (dt.Columns.IndexOf("@xu.Hao") < 0)
   {
    DataColumn dc = new DataColumn("@xu.Hao", System.Type.GetType("System.Int32"));
    dt.Columns.Add(dc);
    dgv.Columns["@xu.Hao"].DisplayIndex = 0;
    dgv.Columns["@xu.Hao"].HeaderText = "#";

    dgv.Columns["@xu.Hao"].SortMode = DataGridViewColumnSortMode.Programmatic;
    dgv.AutoResizeColumn(dgv.Columns["@xu.Hao"].Index); 

    dgv.Columns["@xu.Hao"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
   }
   SumDataGridView(dgv);
  }
  private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
  {//
   DataGridView dgv = (DataGridView)sender;
   if (dgv.Tag == null || e.RowIndex < 0 || e.RowIndex == dgv.Rows.Count - 1) return;

   string col = dgv.Columns[e.ColumnIndex].DataPropertyName;
   if (col == string.Empty) return;
   if (((DataRowView)dgv.Rows[e.RowIndex].DataBoundItem).Row.Table.Columns[col].DataType.IsValueType)
   {
    decimal tal = 0;
    foreach (DataGridViewRow dgvr in dgv.Rows)
    {
     if (dgvr.Index != dgv.Rows.Count - 1)
     {
      string hej = dgvr.Cells[e.ColumnIndex].Value.ToString();
      if (hej != string.Empty) tal += decimal.Parse(hej);
     }
    }
    if (tal == 0)
     dgv[e.ColumnIndex, dgv.Rows.Count - 1].Value = DBNull.Value;
    else
     dgv[e.ColumnIndex, dgv.Rows.Count - 1].Value = tal;
   }
  }
  #endregion  添加DataGridView底行合计数 的四个方法

 

我在项目中多处运行通过,但不知道通用性如何?!
欢迎交流!

作者:阿Q叔叔 (QQ:123889913)



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1501256

 
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:392298次
    • 积分:7231
    • 等级:
    • 排名:第3193名
    • 原创:325篇
    • 转载:71篇
    • 译文:1篇
    • 评论:34条
    最新评论