如何在 DataGridViewCell_Leave 事件中获取 DataGridView 单元格的值?

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

我试图获取事件触发的单元格的值。
当我尝试将 sender 强制转换为 DataGridViewCell 时,会引发异常:

无法将类型为 'System.Windows.Forms.DataGridView' 的对象强制转换为类型 'System.Windows.Forms.DataGridViewCell'。

你有什么建议?
我需要检查该值是否小于20,如果是,则将其增加到21。
6个回答

4
尝试使用theDataGrid[e.RowIndex, e.ColumnIndex].Value进行操作。我预计发送方更可能是DataGridView对象而不是单元格本身。

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

            }
        }

这段代码将获取当前单元格的值,希望这能帮到您。


2
您可以这样获取单元格的值:
dataGridView1[e.ColumnIndex, e.RowIndex].FormattedValue;

2

发送者的类型是DataGridView,因此您可以使用以下行:

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

这是一个非常好的答案,因为有时候会创建一个通用的事件处理程序。也就是说,事件处理程序要服务于多个DataGridView。Dulini Atapattu通过将sender参数查询为DataGridView对象,在这里完成了这个技巧。 - netfed

0
我建议使用EditedFormattedValue属性获取单元格的值,因为在我的测试中,我输入的FormattedValue始终为空。

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;
...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接