GridView空数据时显示表头

方法一

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

如:    

  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="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>

 

原文地址:https://www.cnblogs.com/ilove35/p/2151535.html