日期:2014-05-17  浏览次数:20406 次

gridview合并相同信息行的问题
我想将所有的列中行与行间含有相同的信息就合并成一行,下面的代码i表示要循环的列数,奇怪的是当for (int i = 0; i < 1; i++)第一列还能够合并,可是当我改成for (int i = 0; i < 2; i++),所有的列都不会合并了,也就是一点改变都没有,请大家帮帮我吧,我的代码如下:

C# code
//单元格要合并的行数
    public int intRowSpan = 1;
    //开始合并的索引值
    public int intIndex = 0;
    //记录第一列相等的条件
    private string strText = "";


    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        for (int i = 0; i < 1; i++)
        {
            
            if (e.Row.RowIndex == 0)
            {
                strText = e.Row.Cells[i].Text;
            }
            if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != 0)
            {
                if (e.Row.Cells[i].Text == strText)
                {
                    intRowSpan++;
                    GridView1.Rows[intIndex].Cells[i].RowSpan = intRowSpan;
                    e.Row.Cells[i].Visible = false;
                    
                }
                else
                {
                    intRowSpan = 1;
                    intIndex = e.Row.RowIndex;
                    
                }
                strText = e.Row.Cells[i].Text;

            }
            this.Label1.Text = intRowSpan.ToString();
            
        }
        
        
    }


------解决方案--------------------
C# code

/// <summary>
        /// 合并GridView中某列相同信息的行(单元格) 
        /// </summary>
        /// <param name="GridView1">GridView</param>
        /// <param name="cellNum">第几列</param>
        public static void GroupRows(GridView GridView1, int cellNum)
        {

            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 (gvr.Cells[cellNum].Text == gvrNext.Cells[cellNum].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;

                    }
                }
            }

        }