简体   繁体   中英

merging two datagridview columns into one new column

i want to merge two datagridview columns into one new column.

i first change Visible property of two col to false, then i try to add new col which that value must be formatted as this which col1Value and col2Value is value of above 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 dont know how do this! please help me. my way is true?

You can made your own implementation of the DataGridViewTextBoxCell and override GetFormattedValue method for it. There you can return the formatted value for your column below is an example:

// use custom DataGridViewTextBoxCell as columns's 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, regards

Try this (it works for me):

reportResultForm.dgvResult.Columns.Add("newColumn", "New Column");
        foreach (DataGridViewRow row in reportResultForm.dgvResult.Rows)
        {
            string height= row.Cells["Height"].Value.ToString();
            string width= row.Cells["Width"].Value.ToString();
            string formattedCol= string.Format("{0} per {1}", height, width);
            row.Cells["newColumn"].Value = formattedCol;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM