首先,我不知道这是否可能、正确的方法甚至是否有效,但我希望你们能帮助我,我会尽力解释:
我在 ASPX 页面上有一个 GridView 控件:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" OnRowDataBound="GridView1_RowDataBound" GridLines="None" CssClass="table table-striped" />
我在代码隐藏中创建了一个 DataTable,其中包含以下数据并将其绑定到 Gridview 控件:
-----------------------------------------
| | Name1 | Name2 | Name3 | Name4 |
-----------------------------------------
| Row1 | 1 | 1 | 1 | 1b |
| Row2 | 1a | 2b | 2b | 4b |
| Row3 | 2a | 2c | 2a | 2a |
| Row4 | 1d | 1d | 1d | 4d |
| Row5 | 1e | 1e | 1e | 1e |
| Row6 | 1f | 2f | 3f | 4f |
-----------------------------------------
现在我想合并匹配的列值并添加适当的列跨度。我已将 OnRowDataBound 添加到 GridView 控件,如下所示:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowIndex >= 0)
{
int colSpanValue = 2;
for (int i = 0; i < e.Row.Cells.Count; i++)
{
if (i+1 < e.Row.Cells.Count)
{
if (e.Row.Cells[i].Text == e.Row.Cells[i + 1].Text)
{
e.Row.Cells[i].BackColor = Color.Beige;
e.Row.Cells[i].ColumnSpan = colSpanValue;
e.Row.Cells[i].HorizontalAlign = HorizontalAlign.Center;
e.Row.Cells[i + 1].Visible = false;
colSpanValue++;
}
}
}
}
}
}
所以上面的数据会像这样,像这样。
-----------------------------------------
| | Name1 | Name2 | Name3 | Name4 |
-----------------------------------------
| Row1 | 1 | 1b | <!-- problem
| Row2 | 1a | 2b | 4b |
| Row3 | 2a | 2c | 2a | <!-- problem
| Row4 | 1d | 4d |
| Row5 | 1e |
| Row6 | 1f | 2f | 3f | 4f |
-----------------------------------------
Currently I managed to get this, see screenshot
![enter image description here](https://i.stack.imgur.com/KLorT.png)
然而,这并不是我真正想要看到的,而是期望的,因为 OnRowDataBound 代码块可能没有正确完成。
所以我的问题是:
- 如何合并一行中所有相等的列并向它们添加 colspan?
- 现在,对于棘手的一点,我是否能够对列进行排序,以便正确显示匹配的列单元格? (对此不太确定)
所以理想的结果应该是这样的:
-----------------------------------------
| | Name1 | Name2 | Name3 | Name4 |
-----------------------------------------
| Row1 | 1 | 1b | <!-- problem
| Row2 | 1a | 2b | 4b |
| Row3 | 2a | 2c | 2a | <!-- problem
| Row4 | 1d | 4d |
| Row5 | 1e |
| Row6 | 1f | 2f | 3f | 4f |
-----------------------------------------
更新信息
根据提供的答案更新代码后范康纳斯 and fnostro,两个答案都是正确的并且有效,谢谢您的帮助。
我选择 ConnorsFan 的方法,因为我仍在学习。
colspan 现在是正确的,请参见下面的屏幕截图:
我会试着去弗诺斯特罗的建议通过 DataTable 管理排序部分并将数据重新绑定到 GridView1 并随时通知您。再次感谢您的回答。