C# DataGridViewCellStyle.Format在数字之前或之后添加符号所需的字符串是什么?

C# DataGridViewCellStyle.Format在数字之前或之后添加符号所需的字符串是什么?,c#,winforms,datagridview,format,C#,Winforms,Datagridview,Format,假设我有一个WinFormsDataGridView并且我正在向它添加一个DataGridViewTextBoxColumn,我如何告诉它我想在不修改原始数据本身的情况下,用°符号为其中的所有数据添加后缀 我已经考虑过更改DefaultCellStyle.Format,但我似乎只能得到一个固定数量的数字数字作为符号的后缀,如下所示: new DataGridViewTextBoxColumn { DefaultCellStyle = new DataGridViewCellStyle

假设我有一个WinForms
DataGridView
并且我正在向它添加一个
DataGridViewTextBoxColumn
,我如何告诉它我想在不修改原始数据本身的情况下,用
°
符号为其中的所有数据添加后缀

我已经考虑过更改
DefaultCellStyle.Format
,但我似乎只能得到一个固定数量的数字数字作为符号的后缀,如下所示:

new DataGridViewTextBoxColumn
{
    DefaultCellStyle = new DataGridViewCellStyle
    {
        Format = "0.000°"
    }
}

当我希望
显示为
时,上述操作将导致
4
的原始值显示为
4.000°
,当我希望它显示为
4.1234°
时,
4.1234
显示为
4.123°
。目前我不太关心文本值,但我正在寻找一个通用格式说明符,它基本上会说:“把原始值还给我”,然后我会在格式说明符的末尾添加
°
符号。可以这样做吗?

作为向列应用自定义格式(如添加后缀)的一般解决方案,您可以使用事件。当单元格内容需要格式化以供显示,并且您有机会对其应用自定义格式时,将引发该事件

示例-为DataGridView中的单元格值添加后缀

dataGridView1.DataSource = new[] {
    new { City ="Tehran", Temperature= 4.12345},
    new { City ="Kuala Lumpur", Temperature= 31.12345},
};

dataGridView1.CellFormatting += (obj, args) =>
{
    if (args.RowIndex >= 0 &&     /*Not the row header*/
        args.ColumnIndex == 1 &&  /*Desired column Index*/
        args.Value != null && args.Value != DBNull.Value)
    {
        args.Value = $"{args.Value}°";
    }
};

注意:对于数值,像
“#.##############”
这样的格式也应该起到以下作用:

dataGridView1.Columns["Temperature"].DefaultCellStyle.Format = "#.#############°"

看一看,做一点实验。请密切关注
#
的作用。这很好,但仍然不够理想-如果我不知道我的数字将包含多少个小数位,我如何知道要在格式说明符中放置多少个
#
呢?马特,如果你对答案有任何疑问,请告诉我。