DataGridView.CellParsing 事件

定义

在单元格值已修改的情况下,当单元格退出编辑模式时发生。

C#
public event System.Windows.Forms.DataGridViewCellParsingEventHandler CellParsing;
C#
public event System.Windows.Forms.DataGridViewCellParsingEventHandler? CellParsing;

事件类型

示例

下面的代码示例演示如何处理 CellParsing 事件。 它还演示如何使用 DataGridViewCellParsingEventArgs 类。

C#
// Handling CellParsing allows one to accept user input, then map it to a different
// internal representation.
private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Release Date")
    {
        if (e != null)
        {
            if (e.Value != null)
            {
                try
                {
                    // Map what the user typed into UTC.
                    e.Value = DateTime.Parse(e.Value.ToString()).ToUniversalTime();
                    // Set the ParsingApplied property to 
                    // Show the event is handled.
                    e.ParsingApplied = true;
                }
                catch (FormatException)
                {
                    // Set to false in case another CellParsing handler
                    // wants to try to parse this DataGridViewCellParsingEventArgs instance.
                    e.ParsingApplied = false;
                }
            }
        }
    }
}

注解

默认情况下,控件 DataGridView 将尝试将单元格中显示的用户指定值转换为单元格属性指定的类型中的实际基础单元格 ValueType 值。 此转换使用单元格属性返回的单元格 InheritedStyle 样式的格式设置属性。

如果标准转换不满足你的需求,请处理 CellParsing 事件以提供到所需类型的自定义值转换。

用户可以使用 属性指定的 EditMode 方法进入编辑模式,并可以退出编辑模式,通过移动到另一个单元格或按 ENTER 来提交对单元格所做的任何更改。 按 ESC 将在提交之前还原对值所做的任何更改,并且CellParsing不会发生该事件。 CellParsing仅当实际修改了单元格值时,才会发生该事件,即使最终值与原始值相同也是如此。 调用 方法时 CommitEdit 也会发生这种情况。

处理 CellParsing 事件时,可以自行转换值,也可以自定义默认转换。 例如,可以使用具有所选类型转换器的单元格 ParseFormattedValue 方法自行转换值。 或者,可以让默认类型转换器分析值,但修改 NullValue属性DataGridViewCellParsingEventArgs.InheritedCellStyle返回的 对象的 、 DataSourceNullValueFormatProvider 属性,该属性使用单元InheritedStyle属性初始化。

在自行转换值时,请将属性的初始格式化值 ConvertEventArgs.Value 替换为单元格 ValueType 属性指定的类型中的转换值。 若要指示无需进一步分析,请将 DataGridViewCellParsingEventArgs.ParsingApplied 属性设置为 true

事件处理程序完成后,如果 ConvertEventArgs.Valuenull 或 不是正确类型,或者 DataGridViewCellParsingEventArgs.ParsingApplied 属性为 falseValue 则使用带默认类型转换器的单元 ParseFormattedValue 方法分析 。 此方法的默认实现使用传入的单元格样式的 NullValueDataSourceNullValueFormatProvider 属性分析值。 如果值不等于 NullValue,则使用 FormatProvider 属性和传入的类型转换器分析该值。

若要自定义单元格值转换为格式化值以供显示的转换,请 CellFormatting 处理 事件。

有关如何处理事件的详细信息,请参阅 处理和引发事件

适用于

产品 版本
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另请参阅