DataGridView cell text and cell value
Asked Answered
U

3

5

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

Unbelieving answered 17/1, 2013 at 4:25 Comment(1)
So you're storing text representations of numbers in your DataTable, but you want to display the numeric representation in the DataGridView? Is that what you're saying? Can you provide some more insight as to why you have to do this, and not just have the numbers stored in the data table?Twedy
B
10

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;
        }
    }
}
Boletus answered 17/1, 2013 at 5:56 Comment(2)
Thanks a lot! This is the full answer for meUphill
How can I implement it in radfatagridview?Raja
F
3

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

Like this :

 DataGridView1.Rows[rowIndex].Cells[columnIndex].Tag = 1;
Frisette answered 17/1, 2013 at 4:49 Comment(2)
you can't do this, it's very manual. when assign DataSource, you must assign Tag again.Uphill
Just a comment - the tag can be data bound as well. But the selected answer is the best way to do this, IMO..Journey
M
0

you can create class for it:

public class Item
{
    public int Id { get; }
    public string Name { get; }

    public Item(string name, int id)
    {
        Id = id;
        Name = name;
    }

    public override string ToString()
    {
        return Name;
    }
}

Then

 DataGridView1.Rows[rowIndex].Cells[columnIndex]=new Item("One", 1);
Musaceous answered 10/7, 2019 at 13:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.