GridView数据源中没有数据的时候显示表头

国际惯例 先上代码:前台代码

<asp:GridView ID="grshow" runat="server" AutoGenerateColumns="False" 
        onrowdeleting="grshow_RowDeleting" EmptyDataText="数据为空">
        <Columns>
            <asp:BoundField DataField="name" HeaderText="文件夹名称" />
            <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
        </Columns>
    </asp:GridView>

后台的实现方法,这是实现功能的主要部分

 1 if (dt.Rows.Count == 0)//如果表格中没有数据
 2             {
 3                 dr = dt.NewRow();//新建行
 4                 dt.Rows.Add(dr);//在表格中添加行
 5             }
 6             grshow.DataSource = dt;//绑定数据源到表格中
 7             grshow.DataKeyNames = new string[] { "name" };
 8             grshow.DataBind();//这句话一定要记得加上
 9             int countt = dt.Columns.Count;
10             grshow.Rows[0].Cells.Clear();
11             grshow.Rows[0].Cells.Add(new TableCell());
12             grshow.Rows[0].Cells[0].Text = "没有相关记录";
13             grshow.Rows[0].Cells[0].ColumnSpan = countt;
原文地址:https://www.cnblogs.com/wangyao1135/p/2616234.html