Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the Value of a DataGridViewCell from the Cell_Leave event?

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

I'm trying to get the value of the cell that the event fired from.

An exception is fired when I try to cast sender to a DataGridViewCell:

Unable to cast object of type 'System.Windows.Forms.DataGridView' to type 'System.Windows.Forms.DataGridViewCell'.

What do you recommend I do?

I need to check if the value is less than 20, and if it is, bump it up to 21.

like image 431
Only Bolivian Here Avatar asked May 08 '11 22:05

Only Bolivian Here


4 Answers

Try working with theDataGrid[e.RowIndex, e.ColumnIndex].Value. I'd expect that the sender is more likely to be the DataGridView object rather than the cell itself.

like image 51
Will A Avatar answered Nov 16 '22 03:11

Will A


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

            }
        }

This code will get currentcell value.may this help you.

like image 30
Bikash Katwal Avatar answered Nov 16 '22 04:11

Bikash Katwal


You can get the value of the cell as

dataGridView1[e.ColumnIndex, e.RowIndex].FormattedValue;
like image 2
V4Vendetta Avatar answered Nov 16 '22 02:11

V4Vendetta


sender's type is DataGridView, so you may use the following line:

int cellValue = Convert.ToInt32(((DataGridView)sender).SelectedCells[0].Value);
like image 2
Dulini Atapattu Avatar answered Nov 16 '22 02:11

Dulini Atapattu