Search code examples
c#textdatagridviewcell

DataGridView cell text and cell value


I have a problem with a readonly C# Winform DataGridView.

I have a DataSource for a DataTable and assign it to DataGridView1.DataSource. I want to display cell text by cell value without changing the DataSource.

Ex:

cell value=1 => cell display text="one", 
cell value=2 => cell display text="two"

I want that, if I get:

DataGridView1.Rows[rowIndex].Cells[columnIndex].Value

Then it must be 1 (or 2, or 3) not "one" (or "two", or "three").


Solution

  • You can use CellFormatting event handler.

    private void DataGridView1_CellFormatting(object sender,
        DataGridViewCellFormattingEventArgs e)
    {
        DataGridView dgv = (DataGridView)sender;
        if (dgv.Columns[e.ColumnIndex].Name == "TargetColumnName" &&
            e.RowIndex >= 0 &&
            dgv["TargetColumnName", e.RowIndex].Value is int)
        {
            switch ((int)dgv["TargetColumnName", e.RowIndex].Value)
            {
                case 1:
                    e.Value = "one";
                    e.FormattingApplied = true;
                    break;
                case 2:
                    e.Value = "two";
                    e.FormattingApplied = true;
                    break;
            }
        }
    }