2014-12-11 4 views
2
나는이 게시물에 제공 한 DataGridView에있는 타임 스탬프 포맷에 대한 코드를 사용하고

:어떻게이 C# 함수를 재사용 할 수 있습니까?

Format TimeSpan in DataGridView column

을 ... 내가 코드에 문제가 있어요는 datagridview_Cellformatting 이벤트에 추가 할 . 여기

문제의 코드입니다 :

private void dataGridView_CellFormatting(object sender, 
             DataGridViewCellFormattingEventArgs e) 
{ 
    var formatter = e.CellStyle.FormatProvider as ICustomFormatter; 
    if (formatter != null) 
    { 
     e.Value = formatter.Format(e.CellStyle.Format, 
            e.Value, 
            e.CellStyle.FormatProvider); 
     e.FormattingApplied = true; 
    } 
} 

이 잘 작동하지만, 내 문제는 내가 내 응용 프로그램에서하고있어 데이터 바인딩의 특성상, 나는 10 개의 다른 DataGridView에에이 메소드를 호출 할 필요가있다 사물.

이 메서드는 이벤트 대상을 캡처한다는 것을 알 수 있습니다. 즉, 현재 코드에서이 메서드의 개별 복사본을 10 개 사용 중임을 의미합니다. 이것을 CellFormatting 이벤트의 DataGridview에서 호출 할 수있는 단일 메서드로 통합하는 방법이 있어야합니다.

어떻게 수행 할 수 있는지 아시나요?

+0

"이벤트 대상을 캡처합니까"라는 의미는 무엇입니까? 방법 이름에 의미가 있니? 그것은 단지 메소드 이름 일뿐입니다 ... 여러 객체의 이벤트에 대해 동일한 메소드를 확실히 사용할 수 있습니다. –

+0

Forms Designer의 DataGridView에 대한 속성보기의 이벤트 탭에서 모든 DataGridView에 대해 'Cell Formatting'이벤트를'dataGridView_CellFormatting'으로 설정하면됩니다. 그들은 모두 그 사건에 대해 같은 방법을 사용하게 될 것입니다. – Baldrick

+0

* 상속 *을 사용하십시오. DataGridView에서 클래스를 소유하고 OnCellFormatting() 메서드를 재정의합니다. 짓다. 도구 상자 맨 위에있는 새 컨트롤을 사용하여 기존 컨트롤을 바꿉니다. –

답변

2

확장 프로그램 포함 방법. 데이터 그리드 CellFormatting에

namespace Foo 
{ 
    public static class DataGridExtensions 
    { 
     public static void FormatViewCell(this DataGridViewCellFormattingEventArgs e) 
     { 
      var formatter = e.CellStyle.FormatProvider as ICustomFormatter; 
      if (formatter != null) 
      { 
       e.Value = formatter.Format(e.CellStyle.Format, 
              e.Value, 
              e.CellStyle.FormatProvider); 
       e.FormattingApplied = true; 
      } 
     } 
    } 
} 

using Foo; 

private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    e.FormatViewCell(); 
} 
+0

이것은 트릭을 만들었습니다. 여러분의 도움과 명확한 예에 대해 많은 감사를드립니다. – bmurrell30

1

이 같은 헬퍼 클래스에 저장된 정적 인 방법을 사용할 수 있습니다 :

방법은 InitializeComponent를 한 후 생성자에서 호출 할 수
private static void AddCellFormatting(DataGridView dgView) 
{ 
    dgView.CellFormatting += (sender, e) => 
    { 
     var formatter = e.CellStyle.FormatProvider as ICustomFormatter; 
     if (formatter != null) 
     { 
      e.Value = formatter.Format(e.CellStyle.Format, e.Value, e.CellStyle.FormatProvider); 
      e.FormattingApplied = true; 
     } 
    } 
} 

().

또는 단순히 정적 메서드로 메서드를 사용하고 디자이너에서 추가하십시오.

관련 문제