Merge two datagridview columns into one new column

I want to combine two datagridview columns into one new column.

i first change the visible property of the two columns to false, then I will try to add a new col that should be formatted such that col1Value and col2Value are the values ​​above the columns:

string.Format("{0} per {1}", col1Value, col2Value);

my code

reportResultForm.dgvResult.Columns["Height"].Visible = false;
reportResultForm.dgvResult.Columns["Width"].Visible = false;
DataGridViewColumn col = new DataGridViewColumn();
col.DefaultCellStyle.Format = "{0} per {1}";
col.CellTemplate = new DataGridViewTextBoxCell();
dgvResult.Columns.Add(col);

but I don’t know how to do it! please, help. is my path right?

+3
source share
1 answer

You can create your own implementation of DataGridViewTextBoxCell and override the GetFormattedValue method. Here you can return the formatted value for your column below:

// use custom DataGridViewTextBoxCell as columns template
col.CellTemplate = new MyDataGridViewTextBoxCell();

...

// custom DataGridViewTextBoxCell implementation 
public class MyDataGridViewTextBoxCell : DataGridViewTextBoxCell
{
    protected override Object GetFormattedValue(Object value,
        int rowIndex,
        ref DataGridViewCellStyle cellStyle,
        TypeConverter valueTypeConverter,
        TypeConverter formattedValueTypeConverter,
        DataGridViewDataErrorContexts context)
    {
        return String.Format("{0} per {1}",
            this.DataGridView.Rows[rowIndex].Cells[0].Value,
            this.DataGridView.Rows[rowIndex].Cells[1].Value);
    }
}

hope this helps, believes

+4
source

Source: https://habr.com/ru/post/1725743/


All Articles