DataGridView.CellFormatting 事件

定义

需要设置单元格内容的显示格式时发生。

public:
 event System::Windows::Forms::DataGridViewCellFormattingEventHandler ^ CellFormatting;
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 事件。

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 将尝试将单元格的值转换为适合显示的格式。 例如,它将数字值转换为字符串,以便在文本框单元格中显示。 可以通过设置 Format 属性等DefaultCellStyle属性返回的 的 DataGridViewCellStyle 属性来指示要使用的格式设置约定。

如果标准格式不足,可以通过处理 CellFormatting 事件来自定义格式设置。 此事件允许您指示要用于单元格显示的确切显示值以及单元格样式,如背景色和前景色。 这意味着,无论单元格值本身是否需要格式设置,都可以为任何类型的单元格格式处理此事件。

每次绘制每个单元格时都会发生 该 CellFormatting 事件,因此在处理此事件时应避免长时间处理。 检索单元格 FormattedValue 或调用其 GetFormattedValue 方法时,也会发生此事件。

处理 CellFormatting 事件时,使用 ConvertEventArgs.Value 单元格值初始化 属性。 如果提供从单元格值到显示值的自定义转换,请将 ConvertEventArgs.Value 属性设置为转换后的值,确保新值属于单元格 FormattedValueType 属性指定的类型。 若要指示不需要进一步设置值格式,请将 DataGridViewCellFormattingEventArgs.FormattingApplied 属性设置为 true

事件处理程序完成后,如果 ConvertEventArgs.Valuenull 或 不是正确的类型,或者 DataGridViewCellFormattingEventArgs.FormattingApplied 属性为 falseValue则使用 Format属性返回DataGridViewCellFormattingEventArgs.CellStyle的单元格样式的 、NullValueDataSourceNullValueFormatProvider 属性(使用 cell InheritedStyle 属性初始化)设置 格式。

无论 属性的值 DataGridViewCellFormattingEventArgs.FormattingApplied 如何,属性返回 DataGridViewCellFormattingEventArgs.CellStyle 的 对象的显示属性都用于呈现单元格。

有关使用 CellFormatting 事件进行自定义格式设置的详细信息,请参阅如何:在 Windows 窗体 DataGridView 控件中自定义数据格式

为了避免在处理此事件时造成性能损失,请通过事件处理程序的参数访问单元格,而不是直接访问单元格。

若要自定义格式化的用户指定值转换为实际单元格值的转换,请处理 事件 CellParsing

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

适用于

另请参阅