今天修改旧的项目,发现之前用到的gridview合并单元格代码不适用于模板列。做了修改之后记录下来。
两种方法,第一种适用于所有情况,第二种适用于合并依据列非模板列。
两种方法如下:
方法一:
/// <summary>
/// 合并GridView中某列相同信息的行(单元格) 包含模板列 根据ID=rowspanid 的hiddenfield控件的值来合并。需要合并的 单元格需加上这个控件。根据控件值合并。可以将控件放在某一列,也可以放在每一列。取值的时候分开就行。此方法适合任意列,特别是模板列 无法取cell.text的时候
/// </summary>
/// <param name="GridView1">GridView</param>
/// <param name="cellNums">合并第几列</param>
/// <param name="rowspanid">合并依据控件ID,这里用的hiddenfield控件。只需将ID=rowspanid的hiddenfield控件放在单元格里即可</param>
public static void GroupRows(GridView GridView1, int[] cellNums, string rowspanid = "hfrowspan")
{
foreach (int cellNum in cellNums)
{
int i = 0, rowSpanNum = 1;
while (i < GridView1.Rows.Count - 1)
{
GridViewRow gvr = GridView1.Rows[i];
for (++i; i < GridView1.Rows.Count; i++)
{
GridViewRow gvrNext = GridView1.Rows[i];
if (((HiddenField)gvr.Cells[cellNum].FindControl(rowspanid)).Value == ((HiddenField)gvrNext.Cells[cellNum].FindControl(rowspanid)).Value)
{
gvrNext.Cells[cellNum].Visible = false;
rowSpanNum++;
}
else
{
gvr.Cells[cellNum].RowSpan = rowSpanNum;
rowSpanNum = 1;
break;
}
if (i == GridView1.Rows.Count - 1)
{
gvr.Cells[cellNum].RowSpan = rowSpanNum;
}
}
}
}
}
方法二:
/// <summary>
/// 根据某一列合并其他列。依据的列不能是模板列,否则请用上一个方法↑。
/// </summary>
/// <param name="GridView1">GridView</param>
/// <param name="cellNums">合并第几列,数组</param>
/// <param name="byCellNum">依据第几列</param>
public static void GroupRowsByOne(GridView GridView1, int[] cellNums, int byCellNum)
{
foreach (int cellNum in cellNums)
{
int i = 0, rowSpanNum = 1;
while (i < GridView1.Rows.Count - 1)
{
GridViewRow gvr = GridView1.Rows[i];
for (++i; i < GridView1.Rows.Count; i++)
{
GridViewRow gvrNext = GridView1.Rows[i];
//if (((HiddenField)gvr.Cells[cellNum].FindControl(rowspanid)).Value == ((HiddenField)gvrNext.Cells[cellNum].FindControl(rowspanid)).Value)
if(gvr.Cells[byCellNum].Text== gvrNext.Cells[byCellNum].Text)
{
gvrNext.Cells[cellNum].Visible = false;
rowSpanNum++;
}
else
{
gvr.Cells[cellNum].RowSpan = rowSpanNum;
rowSpanNum = 1;
break;
}
if (i == GridView1.Rows.Count - 1)
{
gvr.Cells[cellNum].RowSpan = rowSpanNum;
}
}
}
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。