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 am trying to get the value of the cell from which the event occurred.

An exception is thrown when I try to apply sender to a DataGridViewCell :

Cannot start an object of type 'System.Windows.Forms.DataGridView' for type 'System.Windows.Forms.DataGridViewCell'.

What do you recommend to me?

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

+6
source share
5 answers

Try working with theDataGrid[e.RowIndex, e.ColumnIndex].Value . I would expect the sender to be a DataGridView object rather than the cell itself.

+4
source
 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 receive the value currentcell. This will help you.

+4
source

You can get the cell value as

 dataGridView1[e.ColumnIndex, e.RowIndex].FormattedValue; 
+2
source

The sender type is DataGridView, so you can use the following line:

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

I made a small option for the _CellClick event.

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

Source: https://habr.com/ru/post/887580/


All Articles