【问题标题】:Concatenate value of 2 columns in datagridview (winform)在datagridview(winform)中连接2列的值
【发布时间】:2019-05-12 14:18:41
【问题描述】:

我有一个包含绑定和未绑定列的 datagridview,我想组合 2 个所需绑定列(a 和 b)的值,因此列 c(未绑定)包含来自 a 和 b 的值

有可能吗?

Nb:抱歉,我不能发布照片以获得更好的解释

谢谢

【问题讨论】:

  • 可能有不同的方式。最简单的可能是使用DataTable 具有 3 列,a、b 和 c,其中 c 是一个表达式列,具有 a+b 作为表达式。

标签: winforms datagridview datagridviewcolumn


【解决方案1】:

可能有不同的方式。最简单的可能是使用具有 3 列 a、b 和 c 的 DataTable,其中 c 是具有 a+b 作为表达式的 expression column

另一种选择是使用DataGridViewRowPrePaint 事件。 (您也可以使用其他一些事件,例如CellFormatting。)

示例 - 表达式列

var dt = new DataTable();
dt.Columns.Add("A", typeof(int));
dt.Columns.Add("B", typeof(string));
dt.Columns.Add("C", typeof(string), "CONVERT(A, System.String) + B");
dt.Rows.Add(1, "One");
dt.Rows.Add(2, "Two");
dataGridView1.DataSource = dt;

示例 - RowPrePaint

dataGridView1.Columns.Add("A", "A");
dataGridView1.Columns.Add("B", "B");
dataGridView1.Columns.Add("C", "C");
dataGridView1.Rows.Add(1, "One");
dataGridView1.Rows.Add(2, "Two");
dataGridView1.RowPrePaint += (s, a) =>
{
    if (a.RowIndex >= 0)
    {
        var g = (DataGridView)s;
        g["C", a.RowIndex].Value = $"{g["A", a.RowIndex].Value}{g["B", a.RowIndex].Value}";
    }
};

【讨论】:

    【解决方案2】:

    您可以在CellFormatting 事件中按需为“c”列单元格生成值:

    private void Grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (e.RowIndex < 0) return;
    
        int cIndex = 2;
        if (e.ColumnIndex != cIndex) return;
    
        var grid = (DataGridView)sender;
        int aIndex = 0, bIndex = 1, row = e.RowIndex;
    
        e.Value = String.Format("{0} {1}", grid[aIndex, row].Value, grid[bIndex, row].Value);
        e.FormattingApplied = true;
    }
    

    【讨论】:

    • 之所以我提到CellFormattingRowPrePaint,但更愿意发布一个关于RowPrePaint的例子,是因为如果你更新前两列的值,第三列不会立即更新,因为第三列不在剪辑绑定中,而RowPrePaint 将始终引发。如果要将CellFormatting 用于可编辑的DataGridView,则需要使格式化单元格无效:grid.InvalidateCell(grid[e.ColumnIndex, e.RowIndex]);
    猜你喜欢
    • 1970-01-01
    • 2013-11-27
    • 2021-11-18
    • 2021-11-03
    • 2014-09-26
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    相关资源
    最近更新 更多