-1

I have a text box through which a "Name" column of a datagridview is searched but at run time exception throws Object reference not set to an instance of an object

 private void textBox1_TextChanged(object sender, EventArgs e)
 {
            string searchstring = textBox1.Text;
            try
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (row.Cells[1].Value.ToString().Contains(searchstring))
                    {
                         Do something   
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
}

enter image description here

shakeel ahmad
  • 129
  • 1
  • 7
  • It could be one of many reasons as to why that code is throwing a null reference exception. Have you tried debugging it and stepping through each line of code inside the scope of the method? That will indicate which object is null. – Jamie Butterworth Oct 18 '18 at 19:06

1 Answers1

0

Check condition before use foreach

Option 1:

for(int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    if (dataGridView1.Rows.Rows[i].Cells[j].Value != null)
                    {
                           foreach (DataGridViewRow row in dataGridView1.Rows)
                            {
                                if (row.Cells[0].Value.ToString().Contains(searchstring))
                                {
                                     //Do something   
                                }
                            }

                    }

                }

            }

Option 2:

if (dataGridView1.Rows.Count > 0)
                    {
                           foreach (DataGridViewRow row in dataGridView1.Rows)
                            {
                                if (row.Cells[0].Value.ToString().Contains(searchstring))
                                {
                                     //Do something   
                                }
                            }

                    }
Dhana
  • 1,618
  • 4
  • 23
  • 39