C# DataGridView单元格文本和单元格值
我对只读C#Winform DataGridView有问题 我为C# DataGridView单元格文本和单元格值,c#,text,datagridview,cell,C#,Text,Datagridview,Cell,我对只读C#Winform DataGridView有问题 我为DataTable提供了一个DataSource,并将其分配给DataGridView1.DataSource。我希望在不更改数据源的情况下按单元格值显示单元格文本 Ex: cell value=1 => cell display text="one", cell value=2 => cell display text="two" 如果我得到: DataGridView1.Rows[rowIndex].Cells[
DataTable
提供了一个DataSource
,并将其分配给DataGridView1.DataSource
。我希望在不更改数据源的情况下按单元格值显示单元格文本
Ex:
cell value=1 => cell display text="one",
cell value=2 => cell display text="two"
如果我得到:
DataGridView1.Rows[rowIndex].Cells[columnIndex].Value
然后它必须是1
(或2
,或3
)而不是“一”(或“二”,或“三”)。我的解决方案是将该值放入DataGridViewCell.Tag属性中
像这样:
DataGridView1.Rows[rowIndex].Cells[columnIndex].Tag = 1;
您可以使用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;
}
}
}
您可以为其创建类:
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;
}
}
然后
你不能这样做,这是非常手动的。分配数据源
时,必须再次分配标记
。只需一条注释-标记也可以是数据绑定的。但是,我认为,选择的答案是最好的方法。因此,您将数字的文本表示形式存储在DataTable中,但您想在DataGridView中显示数字表示形式吗?你是这么说的吗?您能否提供一些更深入的见解,说明为什么您必须这样做,而不仅仅是将数字存储在数据表中?非常感谢!这是我的完整答案我如何在radfatagridview中实现它?
DataGridView1.Rows[rowIndex].Cells[columnIndex]=new Item("One", 1);