C# 带有合并单元格的 GridView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16147963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
GridView with merged cells
提问by himanshu
I need to display data in grid view with merged rows for some columns. Please help me to prepare a grid view in below defined format:

我需要在网格视图中显示某些列的合并行数据。请帮助我准备以下定义格式的网格视图:

And the original data comes from database is in below format:

来自数据库的原始数据格式如下:

Please help me to find best way for doing this task dynamically and efficiently.
请帮助我找到动态有效地完成此任务的最佳方法。
采纳答案by Freelancer
You will have to use RowSpan.
您将不得不使用RowSpan.
Refer following code for it:
请参考以下代码:
protected void GridView1_DataBound1(object sender, EventArgs e)
{
for (int rowIndex = GridView1.Rows.Count - 2;
rowIndex >= 0; rowIndex--)
{
GridViewRow gvRow = GridView1.Rows[rowIndex];
GridViewRow gvPreviousRow = GridView1.Rows[rowIndex + 1];
for (int cellCount = 0; cellCount < gvRow.Cells.Count;
cellCount++)
{
if (gvRow.Cells[cellCount].Text ==
gvPreviousRow.Cells[cellCount].Text)
{
if (gvPreviousRow.Cells[cellCount].RowSpan < 2)
{
gvRow.Cells[cellCount].RowSpan = 2;
}
else
{
gvRow.Cells[cellCount].RowSpan =
gvPreviousRow.Cells[cellCount].RowSpan + 1;
}
gvPreviousRow.Cells[cellCount].Visible = false;
}
}
}
Referance:
参考资料:
https://sites.google.com/site/learning6329/asp-net/gridview-merge-cells
https://sites.google.com/site/learning6329/asp-net/gridview-merge-cells
Pictorial Example As In Question:
有问题的图片示例:
回答by Shridhar Gowda
Simplest way to merge Row-cells of first column is as below. Please note that For Loop is always to be iterated in reverse.
合并第一列的行单元格的最简单方法如下。请注意,For 循环总是要反向迭代。
protected void GridView1_DataBound(object sender, EventArgs e)
{
int RowSpan = 2;
for (int i = GridView1.Rows.Count-2; i >=0 ;i-- )
{
GridViewRow currRow = GridView1.Rows[i];
GridViewRow prevRow = GridView1.Rows[i+1];
if (currRow.Cells[0].Text == prevRow.Cells[0].Text)
{
currRow.Cells[0].RowSpan = RowSpan;
prevRow.Cells[0].Visible = false;
RowSpan += 1;
}
else
RowSpan = 2;
}
}
If you want to merge row-cells of all columns similarly, you can use another "forloop" within outer forloop written above
如果你想合并所有列的行单元格,你可以在上面写的外部 forloop 中使用另一个“forloop”

