Search through datagridview not working - System.NullReferenceException error

若如初见. 提交于 2019-12-25 07:25:35

问题


I am trying to run a search through column 2 (data type: number) on my datagridview but keep getting the following error message:

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

The error is being thrown at if (!string.Equals(row.Cells[1].Value.ToString(), driverNo.Text, StringComparison.OrdinalIgnoreCase))

What is it that I'm doing wrong? I've included my code below:

    void driverSearch()
    {
        CurrencyManager manager = (CurrencyManager)BindingContext[dataGridView1.DataSource];
        manager.SuspendBinding();
        bool shouldNotFilter = string.IsNullOrEmpty(driverNo.Text);
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (shouldNotFilter)
            {
                row.Visible = true;
            }
            else
            {
                if (!string.Equals(row.Cells[1].Value.ToString(), driverNo.Text, StringComparison.OrdinalIgnoreCase))
                {
                    row.Visible = false;
                }
                else
                {
                    row.Visible = true;
                }
            }
        }
        manager.ResumeBinding();
    }

    private void driverNo_KeyUp(object sender, KeyEventArgs e)
    {
        driverSearch();
    }

    private void driverNo_TextChanged(object sender, EventArgs e)
    {
        driverSearch();
    }

    private void driverNo_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
        {
            e.Handled = true;
        }

        driverSearch();
    }

回答1:


try this block in foreach loop:

if (shouldNotFilter)
{
     row.Visible = true;
}
else
{
    if(row.Cells[1].Value == null)
    {
       row.Visible = false;
    }
    else
    {
         if (!string.Equals(row.Cells[1].Value.ToString(), driverNo.Text, StringComparison.OrdinalIgnoreCase))
         {
              row.Visible = false;
         }
         else
         {
              row.Visible = true;
         }
    }
}


来源:https://stackoverflow.com/questions/23154523/search-through-datagridview-not-working-system-nullreferenceexception-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!