DataGridView.CellFormatting 事件

定義

需設定要顯示之儲存格內容的格式時發生。Occurs when the contents of a cell need to be formatted for display.

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 

事件類型

DataGridViewCellFormattingEventHandler

範例

下列程式碼範例顯示如何處理 CellFormatting 事件。The following code example shows how to handle the CellFormatting event.

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

備註

根據預設, DataGridView 控制項會嘗試將儲存格的值轉換成適合顯示的格式。By default, the DataGridView control will attempt to convert a cell's value into a format suitable for display. 例如,它會將數值轉換成字串,以便顯示在文字方塊資料格中。For example, it will convert a numerical value into a string for display in a text box cell. 您可以藉由設定屬性所 Format 傳回之的屬性 DataGridViewCellStyle (例如屬性)來指出要使用的格式化慣例 DefaultCellStyleYou can indicate the formatting convention to use by setting the Format property of the DataGridViewCellStyle returned by properties such as the DefaultCellStyle property.

如果標準格式不完整,您可以藉由處理事件來自訂格式 CellFormattingIf the standard formatting is insufficient, you can customize the formatting by handling the CellFormatting event. 此事件可讓您指定要用於儲存格顯示的確切顯示值以及儲存格樣式,例如背景和前景色彩。This event lets you indicate the exact display value as well as the cell styles, such as background and foreground color, to use for the cell display. 這表示無論資料格的值本身是否需要格式化,您都可以針對任何一種資料格格式來處理這個事件。This means you can handle this event for any kind of cell formatting, regardless of whether the cell value itself needs formatting.

CellFormatting 次繪製每個資料格時,就會發生此事件,因此您應該在處理此事件時避免冗長的處理。The CellFormatting event occurs every time each cell is painted, so you should avoid lengthy processing when handling this event. 當抓取儲存格 FormattedValue 或呼叫其方法時,也會發生此事件 GetFormattedValueThis event also occurs when the cell FormattedValue is retrieved or its GetFormattedValue method is called.

當您處理 CellFormatting 事件時, ConvertEventArgs.Value 屬性會以儲存格值進行初始化。When you handle the CellFormatting event, the ConvertEventArgs.Value property is initialized with the cell value. 如果您提供從資料格值到顯示值的自訂轉換,請將屬性設定為已 ConvertEventArgs.Value 轉換的值,以確保新的值是資料格屬性所指定的型別 FormattedValueTypeIf you provide custom conversion from the cell value to the display value, set the ConvertEventArgs.Value property to the converted value, ensuring that the new value is of the type specified by the cell FormattedValueType property. 若要指出不需要進一步設定值,請將 DataGridViewCellFormattingEventArgs.FormattingApplied 屬性設定為 trueTo indicate that no further value formatting is necessary, set the DataGridViewCellFormattingEventArgs.FormattingApplied property to true.

當事件處理常式完成時,如果 ConvertEventArgs.Valuenull 或不是正確的類型,或 DataGridViewCellFormattingEventArgs.FormattingApplied 屬性為,則 false Value 會使用 Format 屬性所 NullValue 傳回之資料格樣式的、、 DataSourceNullValueFormatProvider 屬性 DataGridViewCellFormattingEventArgs.CellStyle (使用資料格 InheritedStyle 屬性初始化)來格式化。When the event handler completes, if the ConvertEventArgs.Value is null or is not of the correct type, or the DataGridViewCellFormattingEventArgs.FormattingApplied property is false, the Value is formatted using the Format, NullValue, DataSourceNullValue, and FormatProvider properties of the cell style returned by the DataGridViewCellFormattingEventArgs.CellStyle property, which is initialized using the cell InheritedStyle property.

不論屬性的值為何 DataGridViewCellFormattingEventArgs.FormattingApplied ,屬性所傳回之物件的顯示內容 DataGridViewCellFormattingEventArgs.CellStyle 會用來呈現資料格。Regardless of the value of the DataGridViewCellFormattingEventArgs.FormattingApplied property, the display properties of the object returned by the DataGridViewCellFormattingEventArgs.CellStyle property are used to render the cell.

如需使用事件進行自訂格式的詳細資訊 CellFormatting ,請參閱 如何:自訂 Windows Forms DataGridView 控制項中的資料格式For more information about custom formatting using the CellFormatting event, see How to: Customize Data Formatting in the Windows Forms DataGridView Control.

為了避免在處理此事件時發生效能下降,請透過事件處理常式的參數存取資料格,而不是直接存取儲存格。To avoid performance penalties when handling this event, access the cell through the parameters of the event handler rather than accessing the cell directly.

若要自訂將格式化、使用者指定的值轉換成實際的資料格值,請處理 CellParsing 事件。To customize the conversion of a formatted, user-specified value into an actual cell value, handle the CellParsing event.

如需如何處理事件的詳細資訊,請參閱 處理和引發事件For more information about how to handle events, see Handling and Raising Events.

適用於

另請參閱