DataGridView cell is null for CellLeave

I am trying to do some text processing of the contents of a cell when the cell is left. I have the following code, but I get the following exception when I enter some text into a cell and then leave it.

An unhandled exception of type 'System.NullReferenceException' occurred in Program.exe Additional information: Object reference not set to an instance of an object. 

If I break down and the mousehover above .value is really null, but I entered the data in the cell! So what gives?

 private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 3) { string entry = ""; MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()); MakeTextFeet(entry); } if (e.ColumnIndex == 4) { string entry = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString(); MakeTextFeet(entry); } } 
+4
source share
4 answers

Add a few checks:

 DataGridViewCell MyCell = dataGridView1[e.ColumnIndex, e.RowIndex]; if (MyCell != null) { if (MyCell.Value != null) { } } 
+1
source

The cell value is in transition when the CellLeave DataGridView event fires. This is because the DataGridView can be bound to the data source and the change will not be made.

Your best option is to use the CellValueChanged event.

+2
source

I think you want to handle CellEndEdit, not CellLeave.

In CellLeave, the changed value property of the cell is still unchanged (i.e. null for an empty cell, as you noticed, breaking and checking the value). CellEndEdit is set to a new value.

Try something like this in which I tried to generally stick to your source code:

 private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex]; if (e.ColumnIndex == 3 || e.ColumnIndex == 4) { string entry = ""; if (cell.Value != null) { entry = cell.Value.ToString(); } MessageBox.Show(entry); MakeTextFeet(entry); } } 
+1
source

I think you leave an empty cell and try to process its value.

when you leave an empty cell value of the following code:

 string entry = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString(); 
Value

the line in the record will be empty (entry = "") and when you process this value, passing it to another function [MakeTextFeet (record);] it gives you an error.

The solution from my point of view for this problem: →>

put each line of code in the above method and MakeTextFeet (Entry) also in the try block.

When you write a catch block, leave this block empty. For instance.

 try { . . . } catch(Exception) { } 

With this case, your exception will naturally be caught, but since it is void, it will not show you.

0
source

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


All Articles