4

次のコードを使用して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";
            }
        }
    }
}

これにより、データが入力されていないときにエラーインジケータが新しい行の横に表示されるという問題が解決されます。ただし、無効なデータを入力すると、どの行にも、無効なデータを入力した後に初めて行から移動したときにエラーインジケータが表示されません。無効なデータのある行から移動してから元に戻り、もう一度移動すると、エラーインジケーターが表示されます。

4

2 に答える 2

4

OK、私は今それを手に入れたと信じています。次のように、CellEndEdit イベント ハンドラーではなく、CellValidating イベント ハンドラーの開始時に ErrorText を空の文字列に設定します。これは基本的に、寄せられたすべての提案を組み合わせたものです。皆さんに感謝します。すべて役に立ちました。

void centreDataGridView_CellValidating(object sender, 
    DataGridViewCellValidatingEventArgs e)
{
    centreDataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
    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 = "blah blah blah";
            }
        }
    }
}
于 2013-02-28T09:46:39.223 に答える
1

検証された行が aNewRowであるかどうかのチェックを追加し、そうである場合は返します。

void centreDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (centreDataGridView.Rows[e.RowIndex].IsNewRow)
    {
        return; // do not validate row that has no values
    }
    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";
        }
    }
}
于 2013-02-27T13:13:40.353 に答える