Linguagem

DataGridViewCellFormattingEventArgs Classe

Definição

Fornece dados para o CellFormatting evento 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 seguinte exemplo de código demonstra como lidar CellFormattingcom .

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

Observações

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

O CellFormatting evento ocorre sempre que cada célula é pintada, por isso deve evitar um processamento demorado ao lidar com este evento. Este evento também ocorre quando a célula FormattedValue é recuperada ou o seu GetFormattedValue método é chamado.

Quando trata o CellFormatting evento, a ConvertEventArgs.Value propriedade é inicializada com o valor da célula. Se fornecer uma conversão personalizada do valor da célula para o valor de visualização, defina a ConvertEventArgs.Value propriedade para o valor convertido, garantindo que o novo valor é do tipo especificado pela propriedade da célula FormattedValueType . Para indicar que não é necessária mais formatação de valores, defina a DataGridViewCellFormattingEventArgs.FormattingApplied propriedade para true.

Quando o gestor de eventos termina, se o ConvertEventArgs.Value for null ou não for do tipo correto, ou a DataGridViewCellFormattingEventArgs.FormattingApplied propriedade for false, o Value é formatado usando o Format, NullValue, DataSourceNullValue, e FormatProvider as propriedades do estilo de célula devolvido pela DataGridViewCellFormattingEventArgs.CellStyle propriedade, que é inicializada usando a propriedade da célula InheritedStyle .

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

Para mais informações sobre formatação personalizada usando o evento CellFormatting, consulte Como: Personalizar a Formatação de Dados no controlo Windows Forms DataGridView.

Para evitar penalizações de desempenho ao lidar com este evento, acede à célula através dos parâmetros do gestor de eventos em vez de aceder diretamente à célula.

Para personalizar a conversão de um valor formatado e especificado pelo utilizador num valor real de célula, trate do CellParsing evento.

Para mais informações sobre como gerir eventos, consulte Gestão e Levantamento de Eventos.

Construtores

Name Descrição
DataGridViewCellFormattingEventArgs(Int32, Int32, Object, Type, DataGridViewCellStyle)

Inicializa uma nova instância da DataGridViewCellFormattingEventArgs classe.

Propriedades

Name Descrição
CellStyle

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

ColumnIndex

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

DesiredType

Obtém o tipo de dado do valor desejado.

(Herdado de ConvertEventArgs)
FormattingApplied

Recebe ou define um valor que indica se o valor da célula foi formatado com sucesso.

RowIndex

Obtém o índice de linha da célula que está a ser formatada.

Value

Obtém ou define o valor do ConvertEventArgs.

(Herdado de ConvertEventArgs)

Métodos

Name Descrição
Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetHashCode()

Serve como função de hash predefinida.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
ToString()

Devolve uma cadeia que representa o objeto atual.

(Herdado de Object)

Aplica-se a

Ver também