2013-01-05 49 views
5

我有一個包含datgridview的窗體應用程序。我需要對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中輸入整數。由於我有一個列名稱作爲「項目名稱」,它應該作爲文本輸入在代碼中存在問題。當我輸入該項目的名稱時,它會生成一條錯誤消息。其餘的單元格驗證完全正常工作!我該如何編輯代碼,以便它不會產生這個錯誤?

在此先感謝

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 
      } 
     } 
    }