I am having a DataGridView and an Add New Entry button. Each time I add a new entry to the database, I want the program to select the row of the new entry in the DataGridView. After clicking on the Add New Entry button, the below function will be called, with parameters of studentName and date passed to the function. The name of the DataGridView is dvgPontengHistory.
But there is an exception thrown:
Object reference not set to an instance of an object.
on this line:
if(r.Cells["student_name"].Value.ToString().Contains(studentName))
Below is the code:
private void selectRow(string studentName, string date) { int i = 0; foreach (DataGridViewRow r in dgvPontengHistory.Rows) { if(r.Cells["student_name"].Value.ToString().Contains(studentName)) // error in this line { if (r.Cells["date"].Value.ToString().Contains(date)) { dgvPontengHistory.Rows[i].Selected = true; return; } } i++; } }
Any tips on resolving this problem? Thanks.
Probably the case that student_name was null in on of the rows in the result set. That would cause ToString() to fail.
My guess is your update statement is putting null into your table.
Here is how you test:
(set breakpoints on the throw lines).