Search code examples
c#linqdatagridviewlinq-to-dataset

Query a Datagridview.Rows or Dataset using Linq


I have some problem. Since I'm not so experienced with Linq I couldn't figure out how to query my datagridview (or directly to dataset preferably) and show results on another datagridview.

This is where I fill my full datagridview and dataset:

string icerikQuery = "SELECT * FROM [RRSelfServis].[dbo].[talimaticerikler] order by [kod] ASC, [percent] DESC";
//MessageBox.Show(icerikQuery);

SqlDataAdapter icerikadapter = new SqlDataAdapter(icerikQuery, connection);
DataSet icerikSet = new DataSet();
icerikadapter.Fill(icerikSet, "Test_table_icerik");
dataGridView2.DataSource = icerikSet;
dataGridView2.DataMember = "Test_table_icerik";

And here is my query part:

dataGridView4.DataSource = from DataGridViewRow in dataGridView2.Rows
                              where rowView.Row.Field<string>("kod").Value.ToString() == SomeSearchStringVariable
                              orderby rowView.Row.Field<decimal>("percent") descending
                              select row;

But currently I'm having error for dataGridView2.Rows:

Could not find an implementation of the query pattern for source type 'System.Windows.Forms.DataGridViewRowCollection'. 'Where' not found. Consider explicitly specifying the type of the range variable 'DataGridViewRow'.

My first choice would be to query DataSet icerikSet but datagridview would work too.

Thanks in advance.


Solution

  • Take the DataTable from the DataSet you want to search, mark it as enumerable and select the rows matching your search.

    var query = from row in icerikSet.Tables[0].AsEnumerable()
                where row.Field<string>("kod").Equals(SomeSearchStringVariable)
                orderby row.Field<decimal>("percent") descending
                select row;
    

    You can create another DataSet or DataTable from the query and set it as a source for your grid.

    DataTable dt = query.CopyToDataTable();
    [...]