2009-04-27 15 views

答えて

5

このようにErrorProviderを使用することはできませんが、DataGridViewには基本的に同じ考え方の機能が組み込まれています。

アイデアは簡単です。 DataGridViewCellにはErrorTextプロパティがあります。あなたがすることは、OnCellValidatingイベントを処理し、検証に失敗した場合、エラーテキストプロパティを設定し、その赤いエラーアイコンをセルに表示することです。ここにいくつかの擬似コードは次のとおりです。

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

私はErrorTextプロパティを設定しようとしました。実行時に何も起こりません! –

+0

これは奇妙です、それはうまくいくはずです... ErrorTextが空の文字列でないことを確認してください。 –

+1

それは動作するはずです、私はちょうどそれをテストしました。私が考えることができる唯一のことは、DataGridView自体にShowCellErrorsプロパティがあることです。 falseに設定されていないことを確認してください。 – BFree

0

DataGridViewTextBoxColumnのような列を、独自の実装に設定されたCellTemplateを持つdataGridView.Columnsに追加できます(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

あなたは自分のBusinessObjectsへIDataErrorInfoを実装し、あまりにもErrorProviderのためのデータソースとしてのBindingSourceを設定することができます。こうすることで、BusinessObjectの内部の検証がDataGridとすべてのフィールドに表示され、オブジェクトが自動的にバインドされます。

5

私はBFreeの溶液で持っている問題は、セルが編集モードになっているが、私は編集を終了する場合(私の値は、二重であるため)、私はデータフォーマットエラーを取得している間は何も現れないということです。これを解決するには、次のようにErrorProviderを直接セル編集コントロールに貼り付けてください:

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(); 
} 
関連する問題