C# - datagridview doesn't show query result

I need help with a code that's puzzling me: I'm a C # beginner and I'm pounding on some points and need help. In the project I have a simple form and a data source of a linked table in SQL Server. In this form I have a grid and three text boxes: the grid and 2 text boxes are with binding to the same data source; the other text box is to type the search

My goal is for the user to type the search in the text box and to make a filter in bindingsource through LINQ. Follow the code:

private void Search()
{
    if (string.IsNullOrEmpty(toolStripTextBox1.Text))
    {
        var query = from v in coletasDataSet.UF
            select v;
        this.ufBindingSource.DataSource = query.ToList();
    }
    else
    {
        string pesquisa = toolStripTextBox1.Text.ToLower().Trim();
        var query = from v in coletasDataSet.UF
            where v.UF.ToLower().Contains(pesquisa) 
            select v;
        this.ufBindingSource.DataSource = query.ToList();  
    }
}

The problem is that when I search the grid it just does not show any data. It holds the 2 columns (UF and ID_UF) and one blank line. I have debugged and checked the query result and it is coming correctly.

Any suggestion of what might be the problem? Detail: I can not pass the query.ToList () to the grid because it would have the text boxs with the bind showing one set of data and the grid showing another.

1 answer

  • answered 2018-01-13 17:52 Ehsan Ullah Nazir

    Use BindingList

    Binding list provides a generic collection that supports data binding.

    Try Following

         var lstResult = from v in coletasDataSet.UF
                     where v.UF.ToLower().Contains(pesquisa) 
                     select new UF()
                     {
                        Id = u.pk,
                        Username = u.Username
                        ..........                    
                   }).ToList();
    
         var resultSet = new BindingList<UF>(lstResult); // <-- BindingList
    
         //Bind BindingList directly to the DataGrid, no need of BindingSource
         myGrid.DataSource = resultSet;