GridView中数据不满一页时,添加空白行方法

来源:互联网 发布:王者荣耀使用的端口号 编辑:程序博客网 时间:2024/05/16 09:18

因页面展示需要,如果GridView中的数据不满一页时,用空白行补充,自己所用方法为:

1、在数据源中添加空对象。如我绑定的数据源为一个对象的list,一页显示10条数据,如果list中的对象不够10个,就为list添加null对象。

 

            StudyNote sn = new StudyNote();

            sn.Name="test";

            IList<StudyNote> snlist = new List<StudyNote>();
            snlist.Add(sn);

            //添加null

            int nowCount = snlist.Count;
            for (int i = _maxRecord; i > nowCount; i--)
            {
                snlist.Add(null);
            }

2、在gvStudyNote_RowDataBound事件中

 private void gvStudyNote_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

               //添加空行
                if (e.Row.DataItem == null)
                {
                    Label lblNoteName = e.Row.FindControl("lblNoteName") as Label;
                    lblNoteName.Text = "&nbsp";//一定要写&nbsp,否则不会显示空行,
                }
                else
                {
                    StudyNote nowSN = e.Row.DataItem as StudyNote;
                    if (nowStudyNote != null)
                    {
                        Label lblNoteName = e.Row.FindControl("lblNoteName") as Label;
                        lblNoteName.Text = nowSN.name;

                     }
                }
            }
            //自动编号
            if (e.Row.RowIndex != -1)
            {
                int index = e.Row.RowIndex + 1;
                e.Row.Cells[0].Text = index.ToString();
            }

        }

 

另外一种在网上找的方法代码如下,我试了也可以实现,但和有数据的样式不一样,只是一个白板,

protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
    {
        if (GridView1.PageIndex == GridView1.PageCount-1)     //尾页
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // 计算自动填充的行数
                numCount++;
            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                // 计算完毕,在此添加缺少的行
                int toLeft = GridView1.PageSize - numCount;
                int numCols = GridView1.Rows[0].Cells.Count;

                for (int i = 0; i < toLeft; i++)
                {
                    GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
                    for (int j = 0; j < numCols; j++)
                    {
                        TableCell cell = new TableCell();
                        cell.Text = "&nbsp;";
                        row.Cells.Add(cell);
                    }
                    GridView1.Controls[0].Controls.AddAt(numCount + 1 + i, row);
                }
            }
        }
    }