Объединить ячейки GridView
Вступление
Есть много методов в Интернете , решающих задачу , как объединить GridView
строки , если соседние ячейки показывают одинаковые значения. Мой подход не является первым; Однако, я думаю, это довольно универсальный и очень короткие - менее 20 строк кода.
Алгоритм прост: для обхода всех строк, начиная со второго на дне, к вершине. Если значение ячейки такой же , как значение в предыдущей (нижней) строке, затем увеличить RowSpan
и сделать нижнюю ячейку невидимым, и так далее.
Код, который объединяет клетки очень короток:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public
class
GridDecorator
{
public
static
void
MergeRows(GridView gridView)
{
for
(
int
rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)
{
GridViewRow row = gridView.Rows[rowIndex];
GridViewRow previousRow = gridView.Rows[rowIndex + 1];
for
(
int
i = 0; i < row.Cells.Count; i++)
{
if
(row.Cells[i].Text == previousRow.Cells[i].Text)
{
row.Cells[i].RowSpan = previousRow.Cells[i].RowSpan < 2 ? 2 :
previousRow.Cells[i].RowSpan + 1;
previousRow.Cells[i].Visible =
false
;
}
}
}
}
}
|
Последнее действие заключается в добавлении OnPreRender
обработчика событий для GridView
:
1
2
3
4
|
protected
void
gridView_PreRender(
object
sender, EventArgs e)
{
GridDecorator.MergeRows(gridView);
}
|
Вступление
Есть много методов в Интернете , решающих задачу , как объединить GridView
строки , если соседние ячейки показывают одинаковые значения. Мой подход не является первым; Однако, я думаю, это довольно универсальный и очень короткие - менее 20 строк кода.
The algorithm is simple: to bypass all the rows, starting from the second at the bottom, to the top. If a cell value is the same as a value in the previous (lower) row, then increase RowSpan
and make the lower cell invisible, and so forth.
The code that merges the cells is very short:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public
class
GridDecorator
{
public
static
void
MergeRows(GridView gridView)
{
for
(
int
rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)
{
GridViewRow row = gridView.Rows[rowIndex];
GridViewRow previousRow = gridView.Rows[rowIndex + 1];
for
(
int
i = 0; i < row.Cells.Count; i++)
{
if
(row.Cells[i].Text == previousRow.Cells[i].Text)
{
row.Cells[i].RowSpan = previousRow.Cells[i].RowSpan < 2 ? 2 :
previousRow.Cells[i].RowSpan + 1;
previousRow.Cells[i].Visible =
false
;
}
}
}
}
}
|
The last action is to add an OnPreRender
event handler for the GridView
:
1
2
3
4
|
protected
void
gridView_PreRender(
object
sender, EventArgs e)
{
GridDecorator.MergeRows(gridView);
}
|