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 셀 값을 표시에 적합한 형식으로 변환하려고 시도합니다. 예를 들어 숫자 값을 텍스트 상자 셀에 표시할 문자열로 변환합니다. 속성과 같은 DefaultCellStyle 속성에서 반환된 의 DataGridViewCellStyle 속성을 설정 Format 하여 사용할 서식 규칙을 나타낼 수 있습니다.

표준 서식이 부족한 경우 이벤트를 처리하여 서식을 CellFormatting 사용자 지정할 수 있습니다. 이 이벤트를 사용하면 셀 표시에 사용할 정확한 표시 값과 배경색 및 전경색과 같은 셀 스타일을 나타낼 수 있습니다. 즉, 셀 값 자체에 서식이 필요한지 여부에 관계없이 모든 종류의 셀 서식에 대해 이 이벤트를 처리할 수 있습니다.

이벤트는 CellFormatting 각 셀이 그려질 때마다 발생하므로 이 이벤트를 처리할 때 긴 처리를 피해야 합니다. 이 이벤트는 셀 FormattedValue 이 검색되거나 메서드 GetFormattedValue 가 호출될 때도 발생합니다.

이벤트를 처리 CellFormatting 하면 속성이 ConvertEventArgs.Value 셀 값으로 초기화됩니다. 셀 값에서 표시 값으로 사용자 지정 변환을 제공하는 경우 속성을 변환된 값으로 설정 ConvertEventArgs.Value 하여 새 값이 셀 FormattedValueType 속성에 지정된 형식인지 확인합니다. 더 이상 값 서식이 필요하지 않음을 나타내려면 속성을 trueDataGridViewCellFormattingEventArgs.FormattingApplied 설정합니다.

이벤트 처리기가 완료되면 가 올바른 형식이거나 이 아니거나 DataGridViewCellFormattingEventArgs.FormattingApplied 속성이 falseValueConvertEventArgs.Valuenull 는 셀 InheritedStyle 속성을 사용하여 초기화된 속성에서 반환 DataGridViewCellFormattingEventArgs.CellStyle 된 셀 스타일의 , NullValue, DataSourceNullValueFormatProvider 속성을 사용하여 Format형식이 지정됩니다.

의 값 DataGridViewCellFormattingEventArgs.FormattingApplied 에 관계 없이는 속성에서 반환 하는 개체의 표시 속성은 셀을 DataGridViewCellFormattingEventArgs.CellStyle 렌더링 하는 데 사용 됩니다.

이벤트를 사용한 CellFormatting 사용자 지정 서식 지정에 대한 자세한 내용은 방법: Windows Forms DataGridView 컨트롤에서 데이터 서식 사용자 지정을 참조하세요.

이 이벤트를 처리할 때 성능 저하를 방지하려면 셀에 직접 액세스하지 않고 이벤트 처리기의 매개 변수를 통해 셀에 액세스합니다.

서식이 지정된 사용자 지정 값을 실제 셀 값으로 변환하는 것을 사용자 지정하려면 이벤트를 처리합니다 CellParsing .

이벤트를 처리 하는 방법에 대 한 자세한 내용은 참조 하세요. 이벤트 처리 및 발생합니다.

적용 대상

추가 정보