在OnDataBound事件中实现
/// <summary>
/// 数据绑定事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvInfo_DataBound(object sender, EventArgs e)
{
string workGroupId = "";
int startRow = 0;
int endRow = 0;
int rowCount = gvInfo.Rows.Count;
List<GridViewGroupDto> gridViewGroups = new List<GridViewGroupDto>();
foreach (GridViewRow row in gvInfo.Rows)
{
var rowIndex = row.RowIndex;
endRow = rowIndex;
HiddenField hidWorkGroupID = (HiddenField)row.FindControl("hidWorkGroupID");
string currWorkGroupId = hidWorkGroupID.Value;
if (rowIndex == 0)
{
workGroupId = currWorkGroupId;
startRow = rowIndex;
}
else if (rowIndex == rowCount - 1)
{
GridViewGroupDto item = new GridViewGroupDto();
item.WorkGroupID = currWorkGroupId;
item.StartRowIndex = (workGroupId != currWorkGroupId) ? rowIndex : startRow;
item.EndRowIndex = rowIndex;
gridViewGroups.Add(item);
}
else
{
if (workGroupId != currWorkGroupId)
{
GridViewGroupDto item = new GridViewGroupDto();
item.WorkGroupID = workGroupId;
item.StartRowIndex = startRow;
item.EndRowIndex = endRow - 1;
gridViewGroups.Add(item);
workGroupId = currWorkGroupId;
startRow = rowIndex;
}
}
}
//跨行设置
foreach (var data in gridViewGroups)
{
int startIndex = data.StartRowIndex;
int endIndex = data.EndRowIndex;
int diff = endIndex - startIndex + 1;
for (int i = startIndex + 1; i <= endIndex; i++)
{
gvInfo.Rows[i].Cells[0].Visible = false;
gvInfo.Rows[i].Cells[3].Visible = false;
gvInfo.Rows[i].Cells[5].Visible = false;
gvInfo.Rows[i].Cells[6].Visible = false;
}
gvInfo.Rows[startIndex].Cells[0].RowSpan = diff;
gvInfo.Rows[startIndex].Cells[3].RowSpan = diff;
gvInfo.Rows[startIndex].Cells[5].RowSpan = diff;
gvInfo.Rows[startIndex].Cells[6].RowSpan = diff;
}
}
注:我是主要根据绑定数据的某个字段进行分组,记录每组数据的开始和结束行索引,实现跨行
附实现效果图