代码之家  ›  专栏  ›  技术社区  ›  Sergio Rosas

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

  •  2
  • Sergio Rosas  · 技术社区  · 16 年前

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

    我有一个绑定了BindingSource的DataGridView,它有一个自定义类的对象列表。在类的字段中,我有一个字符串字段,我想用它来显示

    Path.GetFileName();
    

    因为它包含了整个文件路径,我想要的是只显示文件名,但在绑定对象中保持文件路径(即绑定数据完整)。

    非常感谢

    2 回复  |  直到 16 年前
        1
  •  5
  •   Quartermeister    16 年前

    使用 DataGridView.CellFormatting DataGridView上的事件。这会给你一个 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;
        }
    }
    
        2
  •  0
  •   Oliver    16 年前

    Binding 班级有一个 Format() Parse() 事件处理程序,您可以在其中定义如何以两种方式格式化数据。