2

I have a datagridview that contains bound and unbound column and i want to combine the value of 2 desired bound column (a and b) so the column c (which is unbound) is contained value from a and b

Is it possible?

Nb : sorry i cant post photos for better explanation

Thanks

Toletolet
  • 21
  • 2
  • 1
    It's possible in different ways. The easiest ,probably, is using `DataTable` having 3 columns, a, b and c, which c is an expression column having a+b as expression. – Reza Aghaei Dec 11 '18 at 15:03

2 Answers2

0

It's possible in different ways. The easiest, probably would be using DataTable having 3 columns, a, b and c, which c is an expression column having a+b as expression.

Another option, is using RowPrePaint event of DataGridView. (You can also use some other events like CellFormatting.)

Example - Expression Column

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;

Example - 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}";
    }
};
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
0

you can generate value for "c" column cells on demand in CellFormatting event:

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;
}
ASh
  • 34,632
  • 9
  • 60
  • 82
  • The reason that I mentioned the `CellFormatting` as well as `RowPrePaint` but preferred to post an example about `RowPrePaint`, is because if you update the value of the first two columns, the third column will not be immediately updated because the third column is not in the clip bound, while `RowPrePaint` will always raise. If you want to use `CellFormatting` for an editable `DataGridView`, you need to invalidate the formatted cell: `grid.InvalidateCell(grid[e.ColumnIndex, e.RowIndex]);`. – Reza Aghaei Dec 11 '18 at 19:42