通过LINQ从gridview获取列值

时间:2023-01-01 13:34:09

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

我有使用以下代码从gridview接收值的代码:

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?

它获取某些单元格包含特定文本的所有行。可以通过LINQ吗?

1 个解决方案

#1


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

我想得到特定单元格包含单词Total的行。可以通过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:

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

#1


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

我想得到特定单元格包含单词Total的行。可以通过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:

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