There is an empty DataGridView which is bound to the data source, and is configured to display two columns Id and Name .

It is necessary to filter the data entered in the TextBox upon request.

I do filtering using

 var selected = db.Products.Where(p => p.Name.ToString().StartsWith(textBox1.Text)).OrderBy(p => p.Name); foreach (var item in selected) { dataGridView1.Rows[i].Cells[0].Value = item.Id; dataGridView1.Rows[i].Cells[1].Value = item.Name; } 

i is a row counter, but when it is 1 , the error "Index beyond the range value" occurs.

Adding a row using the Rows.Add() method also fails, you cannot programmatically add rows to the Grid with data binding.

This method works if the Grid is not bound to data. I need to work with data binding.

  • one
    You can simply update the data source ... dataGridView1.DataSource = selected.ToArray(); - Ev_Hyper
  • @Ev_Hyper, your option works as it should, make out as an answer! I did not immediately figure out how to use it, so I finished it in the evening. - WebMorda
  • Is done. Next time just ask if something is not clear :) - Ev_Hyper

2 answers 2

You can simply update the data source:

 dataGridView1.DataSource = selected.ToArray(); 

    Rather, you need to bring not to Array, but to the list - ToList(); .