Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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").

like image 421
CươngTV Avatar asked Jan 17 '13 04:01

CươngTV


2 Answers

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;
        }
    }
}
like image 160
hority Avatar answered Nov 05 '22 19:11

hority


my solutions is to put the value in DataGridViewCell.Tag property.

Like this :

 DataGridView1.Rows[rowIndex].Cells[columnIndex].Tag = 1;
like image 29
Iswanto San Avatar answered Nov 05 '22 17:11

Iswanto San