Saturday, October 9, 2010

Find out particular row form grid view using LINQ

Usually getting a row from Grid view, we will loop thou the grids row collection and check for Specific conditions.

GridViewRow SelectedRow;

foreach (GridViewRow gr in GridView1.Rows)
{
if ( gr.Cells[1].ToString() == "Value1" && gr.Cells[2].ToString() == "Value2")
{
SelectedRow = gr; break;
}
}

But using LINQ we can write same thing as more readable manners as given below.

GridViewRow SelectedRow = GridView1.Rows.OfType().FirstOrDefault(row => row.Cells[1].ToString() == "Value1" && row.Cells[2].ToString() == "Value2");



No comments: