C# DataGridView 单元格文本和单元格值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14372198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:38:21  来源:igfitidea点击:

DataGridView cell text and cell value

c#textdatagridviewcell

提问by C??ngTV

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

我有一个只读 C# Winform DataGridView 的问题。

I have a DataSourcefor a DataTableand assign it to DataGridView1.DataSource. I want to display cell text by cell value without changing the DataSource.

我有一个DataSourcefor aDataTable并将其分配给DataGridView1.DataSource. 我想按单元格值显示单元格文本而不更改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").

那么它必须是1(或2,或3)不是“一”(或“二”,或“三”)。

采纳答案by hority

You can use CellFormatting event handler.

您可以使用 CellFormatting 事件处理程序。

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;
        }
    }
}

回答by Iswanto San

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

我的解决方案是将值放在 DataGridViewCell.Tag 属性中。

Like this :

像这样 :

 DataGridView1.Rows[rowIndex].Cells[columnIndex].Tag = 1;

回答by Valerii Nozdrenkov

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);