2013-01-05 15 views
5

私はdatgridviewを含むwindowsフォームアプリケーションを持っています。私はそれが負の値を受け入れないようにdatagridviewのセルにセルのバリデーションを強制する必要があります。私はmsdnライブラリから適切なコードを見つけました。C#のDatagridviewセル値の検証

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に入力することしかできません。私はテキストとして入力されるはずの "Item Name"として列名を持っているので、コードに問題があります。アイテムの名前を入力すると、エラーメッセージが表示されます。残りのセルバリデーションは完全に機能しています!このエラーを生成しないように、コードをどのように編集する必要がありますか?事前に

おかげ

Mirfath

答えて

4

DataGridViewCellValidatingEventArgseは、あなたが検証のみをご希望欄に行われていることを確認するためにチェックすることができ.ColIndex性質を持っています。

private void dataGridView1_CellValidating(object sender, 
DataGridViewCellValidatingEventArgs e) { 
    if (e.ColIndex == 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"; 
     } 
    } 
} 
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 
      } 
     } 
    } 
関連する問題