Reputation: 1
This is the table. On the right are the namesI have a gridview that shows a table from the database. I want to search a name in the gridview using a textbox and a button. This is what i have so far. When i want to search I get in a messagebox this: object reference is not set on an instance of an object.
private void btn_zoek_Click(object sender, EventArgs e)
{
string searchValue = tb_SearchOverzicht.Text;
metroGrid1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in metroGrid1.Rows)
{
if (row.Cells[2].Value.ToString().Equals(searchValue))
{
row.Selected = true;
break;
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
Upvotes: 0
Views: 251
Reputation: 677
Check if the values and object you are trying to work with are filled with data and not null
.
In your row
if (row.Cells[2].Value.ToString().Equals(searchValue))
you should check first, if the cell exists and has value, like this:
if(row.Cells[2] != null && row.Cells[2].Value.ToString() == searchValue)
{
// Some code
}
and just to be sure, check if your searchValue
is not empty or without any chars or maybe even correct formatted:
if(!String.IsNullOrWhiteSpace(searchValue))
but I dont think this is necessary here, just nice to have. The goal here is: Not all values have to be filled. It can appear that a cell doesnt have value in that column, the row may be the filter row or even empty, or worst: the grid isn't even initialized. So please try to check if values or objects are filled before using them.
Upvotes: 1