【发布时间】:2016-10-11 15:49:24
【问题描述】:
首先我不知道这是否可能,正确的方法甚至会起作用,但我希望你们能帮助我,我会尽力解释:
我在 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 |
-----------------------------------------
现在我想合并匹配的列值并添加适当的 colspan。我在 GridView 控件中添加了一个 OnRowDataBound,如下所示:
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 |
-----------------------------------------
然而,这并不是我真正希望看到的,而是期望的,因为 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 |
-----------------------------------------
更新信息
根据ConnorsFan和fnostro提供的答案更新代码后,两个答案都正确且有效,感谢您的帮助。 我选择 ConnorsFan 的方法,因为我还在学习。
现在的 colspan 是正确的,请看下面的截图:
我会尝试fnostro 的 建议通过DataTable 管理排序部分并将数据重新绑定到GridView1 并随时通知您。再次感谢您的回答。
【问题讨论】: