DataGridView:格式化值而不实际更改边界数据?

Ser*_*sas 2 c# format datagridview databound datagridviewcellstyle

我一直在网上搜索,但找不到答案。

我有一个BindingSource有界的Da​​taGridView,它具有一个自定义类的对象列表。在该类的字段中,我有一个字符串字段,我想使用

Path.GetFileName();
Run Code Online (Sandbox Code Playgroud)

因为它包含整个文件路径,而我想要的是仅显示文件名,但将文件路径(即,边界数据完整)保留在有界对象中。

有什么方法可以做到这一点(格式,模板,样式等)?因为每当我更改单元格的“值”字段时,它都会更改对象的值(这是逻辑上的)。

提前谢谢了

Qua*_*ter 5

在DataGridView上使用DataGridView.CellFormatting事件。这将为您提供一个DataGridViewCellFormattingEventArgs对象,其中包含有关当前单元格的信息,包括行和列以及未格式化的值。您将Value属性更新为格式化的值,并将FormattingApplied设置为true,然后DataGridView将呈现该值。

像这样:

private void dataGridView1_CellFormatting(object sender, 
    DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 0) // Check for the column you want
    {
        e.Value = Path.GetFileName(e.Value.ToString());
        e.FormattingApplied = true;
    }
}
Run Code Online (Sandbox Code Playgroud)