DataGridView.CellFormatting DataGridView.CellFormatting DataGridView.CellFormatting DataGridView.CellFormatting Event

定义

需要设置单元格内容的显示格式时发生。Occurs when the contents of a cell need to be formatted for display.

public:
 event System::Windows::Forms::DataGridViewCellFormattingEventHandler ^ CellFormatting;
public event System.Windows.Forms.DataGridViewCellFormattingEventHandler CellFormatting;
member this.CellFormatting : System.Windows.Forms.DataGridViewCellFormattingEventHandler 
Public Custom Event CellFormatting As DataGridViewCellFormattingEventHandler 

示例

下面的代码示例演示如何处理CellFormatting事件。The following code example shows how to handle the CellFormatting event.

void dataGridView1_CellFormatting( Object^ /*sender*/, DataGridViewCellFormattingEventArgs^ e )
{
   // If the column is the Artist column, check the
   // value.
   if ( this->dataGridView1->Columns[ e->ColumnIndex ]->Name->Equals( "Artist" ) )
   {
      if ( e->Value != nullptr )
      {
         // Check for the string "pink" in the cell.
         String^ stringValue = dynamic_cast<String^>(e->Value);
         stringValue = stringValue->ToLower();
         if ( (stringValue->IndexOf( "pink" ) > -1) )
         {
            DataGridViewCellStyle^ pinkStyle = gcnew DataGridViewCellStyle;

            //Change the style of the cell.
            pinkStyle->BackColor = Color::Pink;
            pinkStyle->ForeColor = Color::Black;
            pinkStyle->Font = gcnew System::Drawing::Font( "Times New Roman",8,FontStyle::Bold );
            e->CellStyle = pinkStyle;
         }
         
      }
   }
   else
   if ( this->dataGridView1->Columns[ e->ColumnIndex ]->Name->Equals( "Release Date" ) )
   {
      ShortFormDateFormat( e );
   }
}


//Even though the date internaly stores the year as YYYY, using formatting, the
//UI can have the format in YY.  
void ShortFormDateFormat( DataGridViewCellFormattingEventArgs^ formatting )
{
   if ( formatting->Value != nullptr )
   {
      try
      {
         System::Text::StringBuilder^ dateString = gcnew System::Text::StringBuilder;
         DateTime theDate = DateTime::Parse( formatting->Value->ToString() );
         dateString->Append( theDate.Month );
         dateString->Append( "/" );
         dateString->Append( theDate.Day );
         dateString->Append( "/" );
         dateString->Append( theDate.Year.ToString()->Substring( 2 ) );
         formatting->Value = dateString->ToString();
         formatting->FormattingApplied = true;
      }
      catch ( Exception^ /*notInDateFormat*/ ) 
      {
         // Set to false in case there are other handlers interested trying to
         // format this DataGridViewCellFormattingEventArgs instance.
         formatting->FormattingApplied = false;
      }

   }
}
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // If the column is the Artist column, check the
    // value.
    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Artist")
    {
        if (e.Value != null)
        {
            // Check for the string "pink" in the cell.
            string stringValue = (string)e.Value;
            stringValue = stringValue.ToLower();
            if ((stringValue.IndexOf("pink") > -1))
            {
                e.CellStyle.BackColor = Color.Pink;
            }

        }
    }
    else if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Release Date")
    {
        ShortFormDateFormat(e);
    }
}

//Even though the date internaly stores the year as YYYY, using formatting, the
//UI can have the format in YY.  
private static void ShortFormDateFormat(DataGridViewCellFormattingEventArgs formatting)
{
    if (formatting.Value != null)
    {
        try
        {
            System.Text.StringBuilder dateString = new System.Text.StringBuilder();
            DateTime theDate = DateTime.Parse(formatting.Value.ToString());

            dateString.Append(theDate.Month);
            dateString.Append("/");
            dateString.Append(theDate.Day);
            dateString.Append("/");
            dateString.Append(theDate.Year.ToString().Substring(2));
            formatting.Value = dateString.ToString();
            formatting.FormattingApplied = true;
        }
        catch (FormatException)
        {
            // Set to false in case there are other handlers interested trying to
            // format this DataGridViewCellFormattingEventArgs instance.
            formatting.FormattingApplied = false;
        }
    }
}
Private Sub dataGridView1_CellFormatting(ByVal sender As Object, _
    ByVal e As DataGridViewCellFormattingEventArgs) _
    Handles dataGridView1.CellFormatting
    ' If the column is the Artist column, check the
    ' value.
    If Me.dataGridView1.Columns(e.ColumnIndex).Name _
        = "Artist" Then
        If e.Value IsNot Nothing Then

            ' Check for the string "pink" in the cell.
            Dim stringValue As String = _
            CType(e.Value, String)
            stringValue = stringValue.ToLower()
            If ((stringValue.IndexOf("pink") > -1)) Then
                e.CellStyle.BackColor = Color.Pink
            End If

        End If
    ElseIf Me.dataGridView1.Columns(e.ColumnIndex).Name _
        = "Release Date" Then
        ShortFormDateFormat(e)
    End If
End Sub

'Even though the date internaly stores the year as YYYY, using formatting, the
'UI can have the format in YY.  
Private Shared Sub ShortFormDateFormat(ByVal formatting As DataGridViewCellFormattingEventArgs)
    If formatting.Value IsNot Nothing Then
        Try
            Dim dateString As System.Text.StringBuilder = New System.Text.StringBuilder()
            Dim theDate As Date = DateTime.Parse(formatting.Value.ToString())

            dateString.Append(theDate.Month)
            dateString.Append("/")
            dateString.Append(theDate.Day)
            dateString.Append("/")
            dateString.Append(theDate.Year.ToString().Substring(2))
            formatting.Value = dateString.ToString()
            formatting.FormattingApplied = True
        Catch notInDateFormat As FormatException
            ' Set to false in case there are other handlers interested trying to
            ' format this DataGridViewCellFormattingEventArgs instance.
            formatting.FormattingApplied = False
        End Try
    End If
End Sub

注解

默认情况下, DataGridView该控件将尝试将单元格的值转换为适合显示的格式。By default, the DataGridView control will attempt to convert a cell's value into a format suitable for display. 例如,它会将数值转换为字符串,以便在文本框单元格中显示。For example, it will convert a numerical value into a string for display in a text box cell. 可以通过设置Format DataGridViewCellStyle属性返回的属性(如DefaultCellStyle属性)来指示要使用的格式设置约定。You can indicate the formatting convention to use by setting the Format property of the DataGridViewCellStyle returned by properties such as the DefaultCellStyle property.

如果标准格式不充分,可以通过处理CellFormatting事件来自定义格式。If the standard formatting is insufficient, you can customize the formatting by handling the CellFormatting event. 此事件使你可以指示要用于单元显示的精确显示值以及单元格样式,如背景和前景色。This event lets you indicate the exact display value as well as the cell styles, such as background and foreground color, to use for the cell display. 这意味着,无论单元格值本身是否需要设置格式,都可以为任何类型的单元格格式处理此事件。This means you can handle this event for any kind of cell formatting, regardless of whether the cell value itself needs formatting.

CellFormatting次绘制每个单元格时都会发生此事件,因此,在处理此事件时应避免冗长的处理。The CellFormatting event occurs every time each cell is painted, so you should avoid lengthy processing when handling this event. 当检索单元格或FormattedValue调用其GetFormattedValue方法时,也会发生此事件。This event also occurs when the cell FormattedValue is retrieved or its GetFormattedValue method is called.

处理CellFormatting事件时ConvertEventArgs.Value ,将用单元值初始化属性。When you handle the CellFormatting event, the ConvertEventArgs.Value property is initialized with the cell value. 如果提供了从单元值到显示值的自定义转换,请将ConvertEventArgs.Value属性设置为转换后的值,确保新值的类型为 cell FormattedValueType属性指定的类型。If you provide custom conversion from the cell value to the display value, set the ConvertEventArgs.Value property to the converted value, ensuring that the new value is of the type specified by the cell FormattedValueType property. 若要指示不需要进一步设置值格式,请将DataGridViewCellFormattingEventArgs.FormattingApplied属性设置true为。To indicate that no further value formatting is necessary, set the DataGridViewCellFormattingEventArgs.FormattingApplied property to true.

当事件处理程序完成时,如果ConvertEventArgs.Valuenull或不是DataGridViewCellFormattingEventArgs.FormattingApplied正确的类型,或者Format属性为falseValue则使用、 NullValueDataSourceNullValue和格式化。由属性返回的单元格样式的属性,该属性是使用 cell InheritedStyle属性进行初始化的。 DataGridViewCellFormattingEventArgs.CellStyle FormatProviderWhen the event handler completes, if the ConvertEventArgs.Value is null or is not of the correct type, or the DataGridViewCellFormattingEventArgs.FormattingApplied property is false, the Value is formatted using the Format, NullValue, DataSourceNullValue, and FormatProvider properties of the cell style returned by the DataGridViewCellFormattingEventArgs.CellStyle property, which is initialized using the cell InheritedStyle property.

无论DataGridViewCellFormattingEventArgs.FormattingApplied属性的值如何,都将使用DataGridViewCellFormattingEventArgs.CellStyle属性返回的对象的显示属性来呈现单元。Regardless of the value of the DataGridViewCellFormattingEventArgs.FormattingApplied property, the display properties of the object returned by the DataGridViewCellFormattingEventArgs.CellStyle property are used to render the cell.

有关使用CellFormatting事件进行自定义格式设置的详细信息,请参阅如何:自定义 Windows 窗体 DataGridView 控件中的数据格式设置。For more information about custom formatting using the CellFormatting event, see How to: Customize Data Formatting in the Windows Forms DataGridView Control.

若要避免在处理此事件时性能受到影响,请通过事件处理程序的参数而不是直接访问单元来访问单元。To avoid performance penalties when handling this event, access the cell through the parameters of the event handler rather than accessing the cell directly.

若要自定义格式的、用户指定的值到实际单元值的转换,请处理CellParsing事件。To customize the conversion of a formatted, user-specified value into an actual cell value, handle the CellParsing event.

有关如何处理事件的详细信息,请参阅处理和引发事件For more information about how to handle events, see Handling and Raising Events.

适用于

另请参阅