您的位置:首页 > 其它

GridView实现某列中相同值合并(不规则表)

2011-10-10 11:10 281 查看
一、应用背景:

  做项目的时候经常会有这种需求,比如让你罗列一下所有人员的专业信息,要求是第一列列出人员姓名,第二列列出专业信息,当出现很多人员会有多个专业信息的时候,第一列的人员姓名就会重复出现,客户经常会问能不能把它合并了啊?想Excel表那样多好看啊?这个当然可以实现。

二、实现方法:

1. 说明

  我们把对行的合并的方法做个封装,这里会出现两种情况

    1)所要合并的列是非模板列

    2)所要合并的列是模板列

2. 代码实现:

1)普通列

      /// <summary>
/// Gridview列的合并(普通列,不包含模板列)
/// 注意:1.GridView在绑定的时候进行分组和排序,才能让相同的行放在一起
///       2.方法应用的时机,应该在Gridview的DataBound事件中使用
/// </summary>
/// <param name="gv">需要合并的GridView对象</param>
/// <param name="columnIndex">所要合并列的索引</param>
public static void UnitCell(GridView gv, int columnIndex)
{
int i = 0;                  //当前行数
string lastType = string.Empty;        //当前判断是否合并行对应列的值
int lastCell = 0;           //判断最后一个相同值的行的索引
if (gv.Rows.Count > 0)
{
lastType = gv.Rows[0].Cells[columnIndex].Text.ToString();
gv.Rows[0].Cells[columnIndex].RowSpan = 1;
lastCell = 0;
}
for (i = 1; i < gv.Rows.Count; i++)
{
if (gv.Rows[i].Cells[columnIndex].Text == lastType)
{
gv.Rows[i].Cells[columnIndex].Visible = false;
gv.Rows[lastCell].Cells[columnIndex].RowSpan++;
}
else
{
lastType = gv.Rows[i].Cells[columnIndex].Text.ToString();
lastCell = i;
gv.Rows[i].Cells[columnIndex].RowSpan = 1;
}
}
}


2). 模板列:

/// <summary>
/// Gridview列的合并(模板列)
/// </summary>
/// <param name="gv">需要合并的GridView对象</param>
/// <param name="columnIndex">所要合并列的索引</param>
/// <param name="lblName">模板列对象的ID</param>
public static void UnitCell(GridView gv, int columnIndex, string lblName)
{
int i = 0;                  //当前行数
string lastType = string.Empty;        //当前判断是否合并行对应列的值
int lastCell = 0;           //判断最后一个相同值的行的索引
if (gv.Rows.Count > 0)
{
lastType = (gv.Rows[0].Cells[columnIndex].FindControl(lblName) as Label).Text;
gv.Rows[0].Cells[columnIndex].RowSpan = 1;
lastCell = 0;
}
for (i = 1; i < gv.Rows.Count; i++)
{
if ((gv.Rows[i].Cells[columnIndex].FindControl(lblName) as Label).Text == lastType)
{
gv.Rows[i].Cells[columnIndex].Visible = false;
gv.Rows[lastCell].Cells[columnIndex].RowSpan++;
}
else
{
lastType = (gv.Rows[i].Cells[columnIndex].FindControl(lblName) as Label).Text.ToString();
lastCell = i;
gv.Rows[i].Cells[columnIndex].RowSpan = 1;
}
}
}


3). 方法调用:

  方法调用的时机,应该是在GridView的DataBound事件中进行方法的调用。为什么要这样呢?答案很简单,我们经常会分页,这样是为了保证你分页之后,也就是页面跳转的也一页时合并仍然有效。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: