2011-05-08 44 views
6
private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e) 
{ 
    if (e.ColumnIndex > 1) 
    { 
     int cellValue = Convert.ToInt32(((DataGridViewCell)sender).Value); 

     if (cellValue < 20) 
     { 
      ((DataGridViewCell)sender).Value = 21; 
     } 
    } 
} 

我試圖獲取事件觸發的單元格的值。如何從Cell_Leave事件中獲取DataGridViewCell的值?

當我嘗試投senderDataGridViewCell一個例外是觸發:

無法轉換類型 「System.Windows.Forms.DataGridView」的對象 類型 「System.Windows.Forms的.DataGridViewCell」。

你推薦我做什麼?

我需要檢查,如果該值小於20,如果是,撞它高達21

回答

4

嘗試用theDataGrid[e.RowIndex, e.ColumnIndex].Value工作。我期望發件人更可能是DataGridView對象而不是單元格本身。

2

你可以得到單元格的值作爲

dataGridView1[e.ColumnIndex, e.RowIndex].FormattedValue; 
2

發件人的類型是DataGridView的,所以您可以使用下面一行:

int cellValue = Convert.ToInt32(((DataGridView)sender).SelectedCells[0].Value); 
+0

這是一個很好的答案,因爲有時候會創建一個通用的事件處理程序。那是;事件處理程序旨在爲多個DataGridView提供服務。 Dulini Atapattu通過將sender參數作爲DataGridView對象進行查詢來完成這一技巧。 – netfed 2017-11-11 04:30:15

4
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
     { 
      if (dataGridView1.Rows[e.RowIndex].Cells[1].Value != null) 
      { 
       int cellmarks = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value); 
       if (cellmarks < 32) 
       { 
        dataGridView1.Rows[e.RowIndex].Cells[2].Value = "Fail"; 
       } 
       else 
       { 
        dataGridView1.Rows[e.RowIndex].Cells[2].Value = "Pass"; 
       } 

      } 
     } 

此代碼將得到currentcell值。這可以幫助你。

0

我做了一個_CellClick事件的輕微變體。

private void Standard_CellClick(object sender, DataGridViewCellEventArgs e) 
    { 
    if (e.RowIndex >= 0) 
    { 
     int intHeaderId = 0; 
     switch (((DataGridView)sender).Columns[e.ColumnIndex].Name) 
     { 
      case "grcHeaderId": 
       intHeaderId = (int)grvEnteredRecords[grcHeaderId.Index, e.RowIndex].Value; 
       break; 
... 
相關問題