NotSupportedException error while setting value to a DataSource

Posted on

Question :

I have a textBox and I want it, when typing something, the dataSource of my grid provider to 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:

    

Answer :

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 by using the TextChanged event you are causing the data to be fetched in the database to each key that the user presses . This can be extremely problematic if there is a considerable amount of data. It might be a good idea to think a little better and do it in a more appropriate way.

    

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

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

    

Leave a Reply

Your email address will not be published. Required fields are marked *