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.
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.
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.
You can get the value of the cell as
dataGridView1[e.ColumnIndex, e.RowIndex].FormattedValue;
sender's type is DataGridView, so you may use the following line:
int cellValue = Convert.ToInt32(((DataGridView)sender).SelectedCells[0].Value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With