Evaluar y enviar comentarios
MSDN
MSDN Library
 DataGridViewCellFormattingEventHand...
Contraer todo/Expandir todo Contraer todo
Esta página es específica de
Microsoft Visual Studio 2008/.NET Framework 3.5

Hay además otras versiones disponibles para:
Biblioteca de clases de .NET Framework
DataGridViewCellFormattingEventHandler (Delegado)

Actualización: noviembre 2007

Representa el método que controlará el evento CellFormatting de DataGridView.

Espacio de nombres:  System.Windows.Forms
Ensamblado:  System.Windows.Forms (en System.Windows.Forms.dll)
Visual Basic (Declaración)
Public Delegate Sub DataGridViewCellFormattingEventHandler ( _
    sender As Object, _
    e As DataGridViewCellFormattingEventArgs _
)
Visual Basic (Uso)
Dim instance As New DataGridViewCellFormattingEventHandler(AddressOf HandlerMethod)
C#
public delegate void DataGridViewCellFormattingEventHandler(
    Object sender,
    DataGridViewCellFormattingEventArgs e
)
Visual C++
public delegate void DataGridViewCellFormattingEventHandler(
    Object^ sender, 
    DataGridViewCellFormattingEventArgs^ e
)
J#
/** @delegate */
public delegate void DataGridViewCellFormattingEventHandler(
    Object sender,
    DataGridViewCellFormattingEventArgs e
)
JScript
JScript no admite delegados.

Parámetros

sender
Tipo: System..::.Object
Origen del evento.
e
Tipo: System.Windows.Forms..::.DataGridViewCellFormattingEventArgs
DataGridViewCellFormattingEventArgs que contiene los datos del evento.

Controle el evento CellFormatting para personalizar la conversión de un valor de celda en un formato apropiado para mostrar o personalizar el aspecto de una celda dependiendo de su estado o valor.

El evento CellFormatting se produce siempre que se pinta una celda; por tanto, debe evitar procesamientos largos al controlar este evento. El evento también se produce cuando se recupera el valor FormattedValue de la celda o se llama a su método GetFormattedValue.

Cuando se controla el evento CellFormatting, la propiedad ConvertEventArgs..::.Value se inicializa con el valor de la celda. Si proporciona conversión personalizada del valor de celda al valor de presentación, establezca la propiedad ConvertEventArgs..::.Value en el valor convertido, garantizando así que el nuevo valor es del tipo especificado por la propiedad FormattedValueType de la celda. Para indicar que no es necesario realizar más operaciones de formato en el valor, establezca la propiedad DataGridViewCellFormattingEventArgs..::.FormattingApplied en true.

Cuando finaliza el controlador de eventos, si ConvertEventArgs..::.Value es nullNothingnullptrreferencia null (Nothing en Visual Basic), o no es del tipo correcto; o bien, la propiedad DataGridViewCellFormattingEventArgs..::.FormattingApplied es false, se aplica formato a Value utilizando las propiedades Format, NullValue, DataSourceNullValue y FormatProvider del estilo de celda devuelto por la propiedad DataGridViewCellFormattingEventArgs..::.CellStyle, que se inicializa utilizando la propiedad de celda InheritedStyle.

Independientemente del valor de la propiedad DataGridViewCellFormattingEventArgs..::.FormattingApplied, para representar la celda se utilizan las propiedades de presentación del objeto devueltas por la propiedad DataGridViewCellFormattingEventArgs..::.CellStyle.

Para obtener más información sobre el formato personalizado mediante el evento CellFormatting, vea Cómo: Personalizar el formato de los datos en el control DataGridView de formularios Windows Forms.

Para evitar reducciones del rendimiento al controlar este evento, obtenga acceso a la celda a través de los parámetros del controlador de eventos en lugar de hacerlo directamente.

Para personalizar la conversión de un valor con formato especificado por el usuario en un valor de celda real, controle el evento CellParsing.

Para obtener más información sobre la forma de controlar eventos, vea Utilizar eventos.

Cuando se crea un delegado de DataGridViewCellFormattingEventHandler, se identifica el método que controlará el evento. Para asociar el evento al controlador de eventos, se debe agregar una instancia del delegado al evento. Siempre que se produzca el evento, se llama a su controlador, a menos que se quite el delegado. Para obtener más información sobre los delegados de controladores de eventos, vea Eventos y delegados.

En el ejemplo de código siguiente se muestra cómo controlar el evento CellFormatting.

Visual Basic
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
C#
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;
        }
    }
}
Visual C++
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;
      }

   }
}

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

.NET Framework

Compatible con: 3.5, 3.0, 2.0
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker