2

假设我有一个绑定到 BindingSource 的 DataGridView。BindingSource 有一个 MyClass 类的 DataSource

public class MyClass
{
    public double Percentage {get; set;}
    ...
}

DataGridView 将百分比显示为双精度数。所以 19% 的值显示为 0.19,这不是我想要的。

幸运的是,我可以更改列的单元格样式:

dataGridViewCellStyle.Format = "p";

这使得该值根据当前区域性显示为百分比。在我的文化中,0.19 显示为 19%。

到目前为止,一切都很好。但是,如果操作员将此值更改为 18% 并结束编辑单元格,会发生什么情况。

  • 引发事件 CellValidating。在这种情况下,我可以检查输入的文本是否为完美百分比。

然而,紧接着我得到一个异常,字符串“18%”不能被格式化为双精度。

我想我必须告诉 datagridviewCellStyle 使用哪个 formatprivider:

datagridVieCellStyle.FormatProvider = new MyFormatProvider();

class MyFormatProvider : IFormatProvider
{
    public object GetFormat(Type formatType)
    {
        // what to return?
    }
}

问题假设我有以下课程:

public static class PercentStringParser
{
     public static double Parse(string txt);
}

我的格式提供者应该如何调用这个函数?

4

1 回答 1

1

不要使用格式提供程序,而是使用事件 DataGridView.CellParsing

private void OnCellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
    if (e.ColumnIndex == this.percentageDataGridViewTextBoxColumn.Index
        && e.DesiredType == typeof(double)
        && ContainsPercentSign(e.Value.ToString()))
        {   // parsing a percentage to a double
            var formatProvider = this.dataGridView1.Rows[e.RowIndex]
                                     .Cells[e.ColumnIndex]
                                     .InheritedStyle
                                     .FormatProvider;

            try
            {
                e.Value = ParsePercentageToDouble(e.Value.ToString(), formatProvider);
                e.ParsingApplied = true;
            }
            catch (FormatException)
            {
                e.ParsingApplied = false;
            }
        }
        else
        {   // parsing any other column, let the system parse it
            e.ParsingApplied = false;
        }           
    }
}

有关此事件的 MSDN 示例

于 2016-01-07T10:44:40.080 回答