博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

GridView空数据时显示表头

Posted on 2011-08-24 09:23  菠萝35  阅读(352)  评论(0编辑  收藏  举报

方法一

在数据绑定之前,判断查询出来的数据源是否为空,如果为空,则执行添加表头的操作。

如:    

  if (dt.rows.Count == 0)
  {
    ShowEmptyData(dt);
  }

        private void ShowEmptyData(DataTable dt)
        {
            DataTable dtnull = new DataTable();
            dtnull = dt.Clone();//复制一个空的的表,结构如同传递过来的datatable一样
            dtnull.Rows.Add(dtnull.NewRow());//添加一个空行
            grvCustomer.DataSource = dtnull.DefaultView;
            grvCustomer.DataBind();

            grvCustomer.Rows[0].Cells.Clear();
            grvCustomer.Rows[0].Cells.Add(new TableCell());
            grvCustomer.Rows[0].Cells[0].ColumnSpan = dtnull.Columns.Count;
            grvCustomer.Rows[0].Cells[0].Text = "没有相关记录";
            grvCustomer.Rows[0].Cells[0].Style.Add("text-align", "center");

        }

方法二

利用gridview本身自带的空数据模板EmptyDataTemplate

...

<Columns>

</Columns>

        <EmptyDataTemplate>
          <table cellpadding="0" cellspacing="0" style="width:100%; text-align:center">
                <tr style=" font-weight:bold; background-color:#f7fafe;">
                <td style=" border-right:1px solid #c0c0c0">columns1</td>
                <td style=" border-right:1px solid #c0c0c0">columns2</td>
                <td style=" border-right:1px solid #c0c0c0">columns3</td>
                <td style=" border-right:1px solid #c0c0c0">columns4</td>
                <td style=" border-right:1px solid #c0c0c0">columns5</td>
                </tr>
                <tr>
                    <td colspan="5" style=" height:20px; border-top:1px solid #c0c0c0">
                        没有相关记录
                    </td>
                </tr>
            </table>
        </EmptyDataTemplate>