C# DataGridView自定义格式:解析编辑的值

C# DataGridView自定义格式:解析编辑的值,c#,datagridview,iformatprovider,C#,Datagridview,Iformatprovider,假设我有一个绑定到BindingSource的DataGridView。 BindingSource有一个MyClass类的数据源 public class MyClass { public double Percentage {get; set;} ... } DataGridView将百分比显示为双精度。所以19%的值显示为0.19,这不是我想要的 幸运的是,我可以更改列的单元格样式: dataGridViewCellStyle.Format = "p"; 这使得该值根据

假设我有一个绑定到BindingSource的DataGridView。 BindingSource有一个MyClass类的数据源

public class MyClass
{
    public double Percentage {get; set;}
    ...
}
DataGridView将百分比显示为双精度。所以19%的值显示为0.19,这不是我想要的

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

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

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

  • 事件已引发。在这种情况下,我可以检查输入的文本是否为完美百分比
然而,紧接着我得到一个异常,字符串“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);
}

我的格式提供程序应该如何调用此函数?

不要使用格式提供程序,而是使用事件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;
        }           
    }
}