DataGridViewコントロールの個々のセルでErrorProviderをフックするにはどうすればよいですか?
5 に答える
BFree のソリューションで私が抱えている問題は、セルが編集モードのときに何も表示されないことですが、編集を終了するとデータ形式エラーが発生します (値が double であるため)。次のように、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();
}
この方法で 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.
}
}
BusinessObjects に実装IDataErrorInfo
し、BindingSource を ErrorProvider の DataSource として設定することもできます。そうすれば、BusinessObject のインターン検証が DataGrid に表示され、オブジェクトが自動的にバインドされるすべてのフィールドに表示されます。
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;
}
CellTemplate が独自の実装に設定されている (たとえば、DataGridViewTextBoxCell から継承された) 列 (DataGridViewTextBoxColumn など) を dataGridView.Columns に追加できます。次に、実装で、必要に応じて検証を処理し、ニーズに合わせて編集パネルをレンダリングおよび配置します。
http://msdn.microsoft.com/en-us/library/aa730881(VS.80).aspxでサンプルを確認できます。
しかし、もう一度 - もっと簡単な解決策があるかもしれません。