Reputation: 1572
I have a data grid view and a datatable. I'm performing a LINQ query on the data table, and I want to select the specific row that the LINQ query filtered. what is the best way to do so? thank you!
var emp = (from x in dtRoles.AsEnumerable()
where x.Field<string>("ID")==txtEmp.Id
select x).FirstOrDefault();
if (emp != null)
{
//select the specific row in dgvRoles
}
Upvotes: 1
Views: 3398
Reputation: 125207
If you want to select the row in DataGridView
, you can simply change the query to search on DataGridView.Rows
.
To do so, you can use DataBoundItem
of DataGridViewRow
which is the object which is showing in the row. In case you are using a DataTable
as a data source of the control, the data-bound item will be DataRowView
. So you can use such query:
var row = dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(x=>!x.IsNewRow)
.Where(x => ((DataRowView)x.DataBoundItem).Row.Field<string>("Id") == "1")
.FirstOrDefault();
if (row != null)
row.Selected = true;
If for any reason you want to start searching on DataTable
, then first find the DataRow
, then search between Rows
of the DataGridView
to find that row:
var item = dt.AsEnumerable().Where(x => x.Field<string>("Id") == "1").FirstOrDefault();
if (item != null)
{
var row = dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(x => ((DataRowView)x.DataBoundItem).Row == item).FirstOrDefault();
if (row != null)
row.Selected = true;
}
Upvotes: 1
Reputation: 2125
This can be simplified by FirstOrDefault
extension method. By using with Lambda
, we can get the specific row.
var result = dtRoles.AsEnumerable().FirstOrDefault(x => x.Field<string>("ID")== "Sample");//Returns a DataRow
Or, without converting the DataTable
into Enumerable
we can filter the specific row(s) using DataTable.Select
. In this case the return type is a DataTable
.
var result = dtRoles.Select("ID = 'Sample'"); //Returns a dataTable
var row = result[0];//Specific row
C# Fiddle For with sample data
Upvotes: 0