2011-05-08 49 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; 
... 
相关问题