DataGridViewCellFormattingEventArgs Classe

Definição

Fornece dados para o evento CellFormatting de um DataGridView.

public ref class DataGridViewCellFormattingEventArgs : System::Windows::Forms::ConvertEventArgs
public class DataGridViewCellFormattingEventArgs : System.Windows.Forms.ConvertEventArgs
type DataGridViewCellFormattingEventArgs = class
    inherit ConvertEventArgs
Public Class DataGridViewCellFormattingEventArgs
Inherits ConvertEventArgs
Herança
DataGridViewCellFormattingEventArgs

Exemplos

O exemplo de código a seguir demonstra como lidar com 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

Comentários

Manipule o CellFormatting evento para personalizar a conversão de um valor de célula em um formato adequado para exibição ou personalizar a aparência de uma célula dependendo de seu estado ou valor.

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.

Construtores

DataGridViewCellFormattingEventArgs(Int32, Int32, Object, Type, DataGridViewCellStyle)

Inicializa uma nova instância da classe DataGridViewCellFormattingEventArgs.

Propriedades

CellStyle

Obtém ou define o estilo da célula que está sendo formatada.

ColumnIndex

Obtém o índice da coluna da célula que está sendo formatada.

DesiredType

Obtém o tipo de dados do valor desejado.

(Herdado de ConvertEventArgs)
FormattingApplied

Obtém ou define um valor que indica se o valor da célula foi formatado com êxito.

RowIndex

Obtém o índice da linha da célula que está sendo formatado.

Value

Obtém ou define o valor do ConvertEventArgs.

(Herdado de ConvertEventArgs)

Métodos

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Aplica-se a

Confira também