简体   繁体   中英

Searching a name in a gridview C#

This is the table. On the right are the names I 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);
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM