2009-04-27 6 views

답변

5

이 방법으로 ErrorProvider를 사용할 수 있는지 확실하지 않지만 DataGridView에는 기본적으로 동일한 아이디어가 포함 된 기능이 내장되어 있습니다.

아이디어가 간단합니다. DataGridViewCell에는 ErrorText 속성이 있습니다. 당신이하는 일은 OnCellValidating 이벤트를 처리하고 유효성 검사에 실패하면 오류 텍스트 속성을 설정하고 그 빨간색 오류 아이콘을 셀에 표시합니다. 여기에 몇 가지 의사 코드는 다음과 같습니다 당신이 당신은 BusinessObjects에 IDataErrorInfo을 구현하고 너무 ErrorProvider에 대한 데이터 소스로 BindingSource에 설정할 수 있습니다

public Form1() 
{ 
    this.dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating); 
} 

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
     { 
      if (!this.Validates(e.FormattedValue)) //run some custom validation on the value in that cell 
      { 
       this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Error"; 
       e.Cancel = true; //will prevent user from leaving cell, may not be the greatest idea, you can decide that yourself. 
      } 
     } 
+1

. 런타임 중에는 아무 일도 일어나지 않습니다! –

+0

이상하게도 작동해야합니다 ... 오류를 제거하기 때문에 ErrorText가 빈 문자열이 아닌지 확인하십시오. –

+1

작동합니다. 방금 테스트했습니다. 내가 생각할 수있는 유일한 것은 DataGridView 자체에 ShowCellErrors 속성이 있다는 것입니다. false로 설정되지 않았는지 확인하십시오. – BFree

0

DataGridViewTextBoxColumn과 같은 열을 DataGridView.Columns에 추가 할 수 있습니다.이 열은 자체 구현으로 설정된 CellTemplate을가집니다 (예 : DataGridViewTextBoxCell에서 상속). 그런 다음 구현에서 - 원하는대로 유효성 검사를 처리하여 필요에 맞게 편집 패널을 렌더링하고 배치합니다.

http://msdn.microsoft.com/en-us/library/aa730881(VS.80).aspx에서 샘플을 확인할 수 있습니다.

하지만 다시 한 번 간단한 해결책이있을 수 있습니다.

1
private void myGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
{ 
    var dataGridView = (DataGridView)sender; 
    var cell = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex]; 
    if (...) // Validation success 
    { 
     cell.ErrorText = string.Empty; 
     return; 
    } 

    dataGridView.EndEdit(); 
    cell.ErrorText = error; 
    e.Cancel = true; 
} 
2

. 이렇게하면 BusinessObject 내부 인 증 유효성 검사가 DataGrid와 모든 필드에서 자동으로 바인딩 된 개체에 나타납니다.

5

내가 BFree의 솔루션에있는 문제는 셀이 편집 모드에있는 동안 아무것도 나타나지 않지만 편집을 끝내면 데이터 값 오류가 발생합니다 (내 값이 두 배이기 때문에). 이 같은 셀 편집 컨트롤에 직접 ErrorProvider를 부착하여이 문제를 해결 : 나는 ERRORTEXT 속성을 설정 시도

private ErrorProvider ep = new ErrorProvider(); 
private void DGV_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
{ 
    if (e.ColumnIndex < 0 || e.RowIndex < 0) 
     return; 
    double val; 
    Control edit = DGV.EditingControl; 
    if (edit != null && ! Double.TryParse(e.FormattedValue.ToString(), out val)) 
    { 
     e.Cancel = true; 
     ep.SetError(edit, "Numeric value required"); 
     ep.SetIconAlignment(edit, ErrorIconAlignment.MiddleLeft); 
     ep.SetIconPadding(edit, -20); // icon displays on left side of cell 
    } 
} 

private void DGV_CellEndEdt(object sender, DataGridViewCellEventArgs e) 
{ 
    ep.Clear(); 
}