DataGridView.CellFormatting Evento
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Ocorre quando o conteúdo de uma célula precisa de ser formatado para exibição.
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 seguinte exemplo de código 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
Observações
Por defeito, o controlo DataGridView tentará converter o valor de uma célula para um formato adequado para exibição. Por exemplo, converterá um valor numérico numa cadeia para exibição numa célula de caixa de texto. Pode indicar a convenção de formatação a usar definindo a Format propriedade do DataGridViewCellStyle retornado por propriedades como a propriedade DefaultCellStyle .
Se a formatação padrão for insuficiente, pode personalizar a formatação ao tratar do CellFormatting evento. Este evento permite-lhe indicar o valor exato do ecrã, bem como os estilos das células, como a cor de fundo e primeiro plano, a usar para o ecrã da célula. Isto significa que pode gerir este evento para qualquer tipo de formatação de célula, independentemente de o valor da célula necessitar ou não de formatação.
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.
Aplica-se a
Ver também
- DefaultCellStyle
- DataGridViewCellStyle
- Format
- FormatProvider
- NullValue
- DataSourceNullValue
- InheritedStyle
- Value
- FormattedValue
- FormattedValueType
- GetFormattedValue(Object, Int32, DataGridViewCellStyle, TypeConverter, TypeConverter, DataGridViewDataErrorContexts)
- DataGridViewCellFormattingEventHandler
- DataGridViewCellFormattingEventArgs
- FormattingApplied
- CellStyle
- Value
- OnCellFormatting(DataGridViewCellFormattingEventArgs)
- CellParsing
- Estilos de Células no Controle DataGridView do Windows Forms
- Como fazer para: Personalizar a formatação de dados no controlo DataGridView dos Windows Forms
- DataGridView Control (Windows Forms)