How can I get the Value of a DataGridViewCell from the Cell_Leave event?
19,894
Solution 1
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.
Solution 2
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.
Solution 3
sender's type is DataGridView, so you may use the following line:
int cellValue = Convert.ToInt32(((DataGridView)sender).SelectedCells[0].Value);
Solution 4
You can get the value of the cell as
dataGridView1[e.ColumnIndex, e.RowIndex].FormattedValue;
Author by
Only Bolivian Here
Updated on June 13, 2022Comments
-
Only Bolivian Here about 2 years
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 aDataGridViewCell
: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.
-
netfed over 6 yearsThis is a very good answer because one would sometimes create a generic event handler. That is; the event handler is meant to service several DataGridViews. Dulini Atapattu did the trick here by querying the sender parameter as a DataGridView object.