DataGridView.CellFormatting Evento

Definição

Ocorre quando é necessário formatar o conteúdo de uma célula para exibição.

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 

Tipo de evento

Exemplos

O exemplo de código a seguir mostra como lidar com o CellFormatting evento.

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

Comentários

Por padrão, o DataGridView controle tentará converter o valor de uma célula em um formato adequado para exibição. Por exemplo, ele converterá um valor numérico em uma cadeia de caracteres para exibição em uma célula de caixa de texto. Você pode indicar a convenção de formatação a ser usada definindo a Format propriedade do DataGridViewCellStyle retornado por propriedades como a DefaultCellStyle propriedade .

Se a formatação padrão for insuficiente, você poderá personalizar a formatação manipulando o CellFormatting evento. Esse evento permite que você indique o valor de exibição exato, bem como os estilos de célula, como tela de fundo e cor de primeiro plano, a serem usados para a exibição da célula. Isso significa que você pode manipular esse evento para qualquer tipo de formatação de célula, independentemente de o próprio valor da célula precisar de formatação.

O CellFormatting evento ocorre sempre que cada célula é pintada, portanto, você deve evitar o processamento demorado ao lidar com esse evento. Esse evento também ocorre quando a célula FormattedValue é recuperada ou seu GetFormattedValue método é chamado.

Quando você manipula o CellFormatting evento, a ConvertEventArgs.Value propriedade é inicializada com o valor da célula. Se você fornecer conversão personalizada do valor da célula para o valor de exibição, defina a ConvertEventArgs.Value propriedade como o valor convertido, garantindo que o novo valor seja do tipo especificado pela propriedade da célula FormattedValueType . Para indicar que nenhuma formatação de valor adicional é necessária, defina a DataGridViewCellFormattingEventArgs.FormattingApplied propriedade como true.

Quando o manipulador de eventos é concluído, se o ConvertEventArgs.Value é ou não é do tipo correto, ou a propriedade é , o ValueDataGridViewCellFormattingEventArgs.FormattingApplied é falseformatado usando as Formatpropriedades , NullValue, DataSourceNullValuee FormatProvider do estilo de célula retornado pela DataGridViewCellFormattingEventArgs.CellStyle propriedade , que é inicializada usando a propriedade cellInheritedStyle.null

Independentemente do valor da DataGridViewCellFormattingEventArgs.FormattingApplied propriedade, as propriedades de exibição do objeto retornado pela DataGridViewCellFormattingEventArgs.CellStyle propriedade são usadas para renderizar a célula.

Para obter mais informações sobre a formatação personalizada usando o CellFormatting evento, consulte Como personalizar a formatação de dados no Windows Forms Controle DataGridView.

Para evitar penalidades de desempenho ao manipular esse evento, acesse a célula por meio dos parâmetros do manipulador de eventos em vez de acessar a célula diretamente.

Para personalizar a conversão de um valor formatado especificado pelo usuário em um valor de célula real, manipule o CellParsing evento.

Para obter mais informações sobre como lidar com eventos, consulte Manipulando e levantando eventos.

Aplica-se a

Confira também