次のコードを使用してDataGridViewを検証しています...
void centreDataGridView_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
if (centreDataGridView.Columns[e.ColumnIndex].Name == "code")
{
Regex codeRegex = new Regex("^[0-9]{5}[0-9A-Z]$");
if (!codeRegex.IsMatch(e.FormattedValue.ToString()))
{
centreDataGridView.Rows[e.RowIndex].ErrorText = "error text here";
}
}
}
void centreDataGridView_CellEndEdit(object sender,
DataGridViewCellEventArgs e)
{
centreDataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
}
これは機能しますが、新しい行を入力してからデータを入力せずに再度残すと、エラー警告アイコンが新しい行セレクターに表示されたままになります。どうすればクリアできますか?
これまでに受け取った提案に基づいて、上記のコードを次のように変更しました...
void centreDataGridView_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
if (centreDataGridView.Columns[e.ColumnIndex].Name == "code")
{
if (!(centreDataGridView.Rows[e.RowIndex].IsNewRow) ||
(e.FormattedValue.ToString() != string.Empty))
{
Regex codeRegex = new Regex("^[0-9]{5}[0-9A-Z]$");
if (!codeRegex.IsMatch(e.FormattedValue.ToString()))
{
centreDataGridView.Rows[e.RowIndex].ErrorText = "error text here";
}
}
}
}
これにより、データが入力されていないときにエラーインジケータが新しい行の横に表示されるという問題が解決されます。ただし、無効なデータを入力すると、どの行にも、無効なデータを入力した後に初めて行から移動したときにエラーインジケータが表示されません。無効なデータのある行から移動してから元に戻り、もう一度移動すると、エラーインジケーターが表示されます。