【问题标题】:DataGridView custom formatting: parse edited valueDataGridView 自定义格式:解析编辑值
【发布时间】:2016-01-06 16:23:01
【问题描述】:

假设我有一个绑定到 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);
}

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

【问题讨论】:

    标签: c# datagridview iformatprovider


    【解决方案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 example about this event

    【讨论】:

      猜你喜欢
      • 2012-04-05
      • 2014-02-27
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多