Notsupportedexception error when setting value to a Datasource

Asked

Viewed 35 times

3

I have a textbox and want, when typing something, the datasource of my gridFornecedor be updated.

I’m using the code below:

private void txtNome_TextChanged(object sender, EventArgs e)
{
    gridFornecedor.DataSource = modelOff.fornecedors.Where(p => p.nome.Contains(txtNome.Text));
}

I get the error below:

inserir a descrição da imagem aqui

2 answers

6


The problem is written in the error, the return of its expression is a query and not concrete data.

Call .ToList() to materialize the data

gridFornecedor.DataSource = modelOff.fornecedors
                                    .Where(p => p.nome.Contains(txtNome.Text)).ToList();

Notice that using the event TextChanged you are causing the data to be searched in the each key the user presses. This can be extremely problematic if there is a considerable amount of data. Maybe it’s a good idea to think a little better and do it in a more appropriate way.

  • How do you suggest I search the bank? By clicking a button? I do so because it is more interactive.

  • 1

    Maybe it’s better. Understand that I only warned you because could be a problem, doesn’t mean it already is. If you know that data traffic won’t be great and that won’t be a problem, keep it even =D

3

You need to materialize the return of the database data through a conversion to an object or collection. Following the suggestion of the error message, try calling the method ToList() after applying the Where:

private void txtNome_TextChanged(object sender, EventArgs e)
{
    gridFornecedor.DataSource = modelOff.fornecedors.Where(p => p.nome.Contains(txtNome.Text)).ToList();
}
  • 2

    Materialize all data and then filter?

  • The order of Tolist() was wrong even, already corrected.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.