Harshit
Harshit

Reputation: 5157

Get column value from gridview via LINQ

I have the code which receives the values from the gridview using this code :

foreach (GridViewRow gr in MainGridView.Rows)
{

     if (MainGridView.Rows[gr.RowIndex].Cells[1].Text == "Total" || MainGridView.Rows[gr.RowIndex].Cells[0].Text == "Total")
             MainGridView.Rows[gr.RowIndex].Font.Bold = true;
}

It gets all the rows whose certain cell contain the particular text. Is it possible via LINQ?

Upvotes: 2

Views: 2740

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460288

I want to get the rows where the particular cells contain the word Total. Is it possible via LINQ?

IEnumerable<GridViewRow> rows = MainGridView.Rows.Cast<GridViewRow>()
    .Where(row => row.Cells[0].Text == "Total" || row.Cells[1].Text == "Total");

or, a little bit more maintainable:

int[] cells = { 0, 1 };
IEnumerable<GridViewRow> rows = MainGridView.Rows.Cast<GridViewRow>()
    .Where(row => cells.Any(c => row.Cells[c].Text == "Total"));

If you want to compare case insensitively(takes also "total"):

.Where(row => cells.Any(c => row.Cells[c].Text.Equals("Total", StringComparison.InvariantCultureIgnoreCase)));

If you now want to make all those rows bold use a foreach:

foreach(var row in rows)
    row.Font.Bold = true;

Upvotes: 2

Related Questions