DataGridView.CellFormatting Esemény

Definíció

Akkor fordul elő, ha egy cella tartalmát megjelenítésre kell formázni.

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 

Eseménytípus

Példák

Az alábbi példakód bemutatja, hogyan kezelheti az eseményt 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

Megjegyzések

Alapértelmezés szerint a DataGridView vezérlő megkísérli egy cella értékének megjelenítésre alkalmas formátummá konvertálását. Egy numerikus értéket például sztringgé alakít át egy szövegdobozcellában való megjelenítéshez. A használni kívánt formázási konvenciót a tulajdonságok, például Format a DataGridViewCellStyle tulajdonság által visszaadott tulajdonság DefaultCellStyle beállításával jelezheti.

Ha a szokásos formázás nem megfelelő, testre szabhatja a formázást az CellFormatting esemény kezelésével. Ez az esemény lehetővé teszi a pontos megjelenítési értéket, valamint a cellastílusokat, például a háttér- és előtérszínt a cellamegjelenítéshez. Ez azt jelenti, hogy bármilyen cellaformázás esetén kezelheti ezt az eseményt, függetlenül attól, hogy magának a cellaértéknek szüksége van-e formázásra.

Az CellFormatting esemény minden alkalommal megtörténik, amikor minden cella meg van festve, ezért kerülnie kell a hosszadalmas feldolgozást az esemény kezelésekor. Ez az esemény akkor is előfordul, ha a cella FormattedValue lekérése vagy metódusának meghívása GetFormattedValue történik.

Az esemény kezelésekor a CellFormattingConvertEventArgs.Value tulajdonság inicializálva lesz a cellaértékkel. Ha egyéni átalakítást biztosít a cellaértékről a megjelenítési értékre, állítsa a ConvertEventArgs.Value tulajdonságot a konvertált értékre, biztosítva, hogy az új érték a cellatulajdonság FormattedValueType által megadott típusú legyen. Ha azt szeretné jelezni, hogy nincs szükség további értékformázásra, állítsa a tulajdonságot a DataGridViewCellFormattingEventArgs.FormattingApplied következőre true: .

Ha az eseménykezelő befejeződött, vagy ConvertEventArgs.Value nem a megfelelő típusú, vagy null a tulajdonság az, akkor a DataGridViewCellFormattingEventArgs.FormattingApplied program falsea tulajdonság által visszaadott ValueFormatNullValueDataSourceNullValue cellastílus, illetve a cellatulajdonság FormatProvider használatával DataGridViewCellFormattingEventArgs.CellStyle inicializált cellastílus tulajdonságait használja.InheritedStyle

A tulajdonság értékétől DataGridViewCellFormattingEventArgs.FormattingApplied függetlenül a tulajdonság által DataGridViewCellFormattingEventArgs.CellStyle visszaadott objektum megjelenítési tulajdonságai a cella megjelenítésére szolgálnak.

A CellFormatting eseményt használó egyéni formázásról további információt a Hogyan is: Adatformázás testreszabása a Windows Forms DataGridView vezérlőben.

Az esemény kezelésekor a teljesítménybeli büntetések elkerülése érdekében a cella elérése az eseménykezelő paraméterein keresztül történik, nem pedig közvetlenül a cellához való hozzáféréssel.

Ha testre szeretné szabni egy formázott, felhasználó által megadott érték tényleges cellaértékké alakítását, kezelje az eseményt CellParsing .

Az események kezelésével kapcsolatos további információkért lásd: Események kezelése és emelése.

A következőre érvényes:

Lásd még