GridView没有数据时显示表头

 在开发中,遇到一个问题。我使用一个gridview作数据查询。表头上多列都带有dropdownlist用来选择过滤条件。当查询的数据集为空时,我的表头也显示不出来了。用户无法修改过滤条件。在网上找了一下,发现了不少好的方法。
1 使用EmptyDataTemplate,

如果你的表头只是html的文本,没有任何控件。你可以在表头显示出来的时候,拷贝表头部分的html,然后放到EmptyDataTemplate里面。

类似:

<EmptyDataTemplate>

<Table>

<tr>

<td>第一列</td> <td>二列</td>

</tr>

</Table>

</EmptyDataTemplate>

不过对于我这种情况,由于我的表头里有控件,这种办法就不好使了。

有人还提出了类似的方法,如定义一个panel,里面是数据为空时的显示内容,在数据为空时,显示此panel。其实还是使用gridview自己提供的方法最好。

2 在结果数据为空时,自己建一个只有一行的空数据集。重新绑定到gridview

下面是我的代码

       我的数据源是sqldatasource,所以处理麻烦一些。 

        GridView1.DataSourceID = "";  //gridview不允许同时指定DataSourceID 和DataSource 
        GridView1.DataSource = DataSource_PipeLine;
        GridView1.DataBind();
        //if there is no data found, change the datasource to a empty datasource, so the header will visible
        if (GridView1.Rows.Count == 0)
        {

            //在创建时,我利用了sqldatasource的connect string 和select command,将来改变数据库连接或sql不会影响这段代码
            using (System.Data.SqlClient.SqlConnection connect = new System.Data.SqlClient.SqlConnection(DataSource_PipeLine.ConnectionString))
            {
                connect.Open();
                DataTable dt = new DataTable();
                System.Data.SqlClient.SqlDataAdapter adpter = new System.Data.SqlClient.SqlDataAdapter(DataSource_PipeLine.SelectCommand, connect);
                adpter.Fill(dt);
                DataRow dr = dt.NewRow();
                dt.Clear();
                dt.Rows.Add(dr);
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值