将公式单元格应用于DataGridview [英] Apply Formula Cell to a DataGridview

查看:80
本文介绍了将公式单元格应用于DataGridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 DataGridView 中添加公式单元格。是否有任何自定义的 DataGridView 来做到这一点?

I want to add formula cell in a DataGridView. Is there any custom DataGridView to do this?

示例:

grid[4, column].Text = string.Format("=MAX({0}6:{0}{1})", columnAsString, grid.RowCount);


推荐答案

是否有任何自定义DataGridView可以执行此操作?

非主题,但如果您要查找自定义控件,请查看免费.NET电子表格控件。它还支持公式

Off-topic, but if you are looking for a custom control, take a look at Free .NET Spreadsheet Control. Also it supports formula.

如果编写计算代码适合您

如果编写计算代码适合您可以根据其他一些单元格的值来计算单元格的值,可以使用 DataGridView CellFormatting 事件并将计算逻辑在那里。同时处理 CellEndEdit 并调用 InvalidateCell Invalidate 强制更新

If writing code for calculation is an option for you, to calculate value of a cell based on values of some other cells you can use CellFormatting event of DataGridView and put calculation logic there. Also handle CellEndEdit and call InvalidateCell or Invalidate to force update value of cell after each in reference cells.

这里是一个示例:

void Form1_Load(object sender, EventArgs e)
{
    Random r = new Random();
    var dt = new DataTable();
    dt.Columns.Add("A", typeof(int));
    dt.Columns.Add("B", typeof(int));
    for (int i = 0; i < 10; i++)
        dt.Rows.Add(r.Next(100));
    grid.DataSource = dt;
    grid.CellFormatting += grid_CellFormatting;
    grid.CellEndEdit += grid_CellEndEdit;
}
void grid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    grid.Invalidate();
}
void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    var grid = sender as DataGridView;
    var parameterColumnName = "A";       //Parameter column name
    var start = 0;                       //Start row index for formula
    var end = grid.RowCount - 1;         //End row index for formula
    var resultRowIndex = 0;              //Result row index
    var resultColumnName = "B";          //Result column name
    if (e.RowIndex == resultRowIndex &&
        grid.Columns[e.ColumnIndex].Name == resultColumnName)
    {
        var list = Enumerable.Range(start, end - start + 1)
              .Select(i => grid.Rows[i].Cells[parameterColumnName].Value)
              .Where(x => x != null && x != DBNull.Value)
              .Cast<int>();
        if (list.Any())
            e.Value = list.Max();
    }
}

注意

该解决方案不仅限于 DataTable ,它将与 DataSource 用于 DataGridView ,并且在此解决方案中可以使用任何类型的数据源。

The solution is not limited to DataTable, it will work regardless of the DataSource which you use for DataGridView and you can use any kind of data source in this solution.

这篇关于将公式单元格应用于DataGridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆