共用方式為


DataGridView.CellFormatting 事件

定義

需設定要顯示之儲存格內容的格式時發生。

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 

事件類型

範例

下列程式碼範例示範如何處理 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

備註

根據預設, DataGridView 控制項會嘗試將儲存格的值轉換成適合顯示的格式。 例如,它會將數值轉換成字串,以在文字方塊儲存格中顯示。 您可以藉由設定 Format 屬性所傳回的 DataGridViewCellStyle 屬性,來指出要使用的格式設定慣例,例如 DefaultCellStyle 屬性。

如果標準格式設定不足,您可以藉由處理 CellFormatting 事件來自訂格式設定。 此事件可讓您指出要用於儲存格顯示的確切顯示值,以及儲存格樣式,例如背景和前景色彩。 這表示不論儲存格值本身是否需要格式化,您都可以針對任何類型的儲存格格式處理此事件。

每次 CellFormatting 繪製儲存格時都會發生此事件,因此您應該避免在處理此事件時進行冗長的處理。 當擷取儲存格 FormattedValue 或其 GetFormattedValue 方法被呼叫時,也會發生這個事件。

當您處理 CellFormatting 事件時, ConvertEventArgs.Value 屬性會以儲存格值初始化。 如果您提供從儲存格值到顯示值的自訂轉換,請將 ConvertEventArgs.Value 屬性設定為已轉換的值,以確保新值屬於儲存格 FormattedValueType 屬性所指定的類型。 若要指出不需要進一步的值格式設定,請將 DataGridViewCellFormattingEventArgs.FormattingApplied 屬性設定為 true

當事件處理常式完成時,如果 ConvertEventArgs.Valuenull 或 不是正確的型別,或 DataGridViewCellFormattingEventArgs.FormattingApplied 屬性為 falseValue 則會使用 Format 屬性所 DataGridViewCellFormattingEventArgs.CellStyle 傳回之儲存格樣式的 、 DataSourceNullValueNullValue 、 和 FormatProvider 屬性進行格式化,而該屬性會使用儲存格 InheritedStyle 屬性初始化。

不論 屬性的值 DataGridViewCellFormattingEventArgs.FormattingApplied 為何,屬性所 DataGridViewCellFormattingEventArgs.CellStyle 傳回物件的顯示內容都會用來轉譯儲存格。

如需使用 CellFormatting 事件自訂格式的詳細資訊,請參閱How to: Custom DataGridView Control 中的Windows Forms資料格式設定。

若要避免處理此事件時的效能負面影響,請透過事件處理常式的參數來存取儲存格,而不是直接存取儲存格。

若要自訂格式化、使用者指定的值轉換成實際儲存格值,請處理 CellParsing 事件。

如需如何處理事件的詳細資訊,請參閱 處理和引發事件

適用於

另請參閱