8

datgridview を含む Windows フォーム アプリケーションがあります。負の値を受け入れないように、datagridview セルにセル検証を適用する必要があります。msdn ライブラリから適切なコードを見つけました。

private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ErrorText = "";
int newInteger;

// Don't try to validate the 'new row' until finished  
// editing since there 
// is not any point in validating its initial value. 
if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
if (!int.TryParse(e.FormattedValue.ToString(),
    out newInteger) || newInteger < 0)
{
    e.Cancel = true;
    dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a Positive integer";
}
}

残念ながら、このコードでは、datagridview に入力できるのは整数のみです。テキストとして入力されるはずの「アイテム名」として列名があるため、コードに問題があります。アイテムの名前を入力するとエラー メッセージが表示されます。残りのセル検証は完全に機能しています。このエラーが発生しないようにコードを編集するにはどうすればよいですか?

前もって感謝します

ミルファス

4

2 に答える 2

9

DataGridViewCellValidatingEventArgs e検証が.ColumnIndex目的の列でのみ行われることを確認するためにチェックできるプロパティがあります。

private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e) {
    if (e.ColumnIndex == dataGridView1.Columns["MyNumericColumnName"].Index) {
        dataGridView1.Rows[e.RowIndex].ErrorText = "";
        int newInteger;

        // Don't try to validate the 'new row' until finished  
        // editing since there 
        // is not any point in validating its initial value. 
        if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
        if (!int.TryParse(e.FormattedValue.ToString(),
            out newInteger) || newInteger < 0)
        {
            e.Cancel = true;
            dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a Positive integer";
        }
    }
}
于 2013-01-05T14:48:28.700 に答える
0

これを試してみてください。

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        if (dataGridView1.IsCurrentCellDirty)
        {
            if (e.ColumnIndex == 0) //<-Column for String
            {
                Console.WriteLine(dataGridView1[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString());
                //Your Logic here
            }
            if (e.ColumnIndex == 1) //<-Column for Integer
            {
                Console.WriteLine(dataGridView1[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString());
                //Your Logic here
            }
        }
    }
于 2013-01-05T15:13:59.833 に答える