处理GridView数据源(DataTable)为空行(转)

///
    /// 绑定GridView
    ///

private void BindGridView()
    {
        DataTable dt = RunQuery(string.Format("Select NodeValue, NodeText From TreeViewTable where 1 > 2")).Tables[0];

        if (dt.Rows.Count == 0)
        {
            //生成DataRow对象
            DataRow row = dt.NewRow();

            foreach (DataColumn column in dt.Columns)
            {
                //重新设置AllowDBNull属性
                column.AllowDBNull = true;
                //显式赋值成null
                row[column] = DBNull.Value;
            }
            //将DataRow对象添加至table中
            dt.Rows.Add(row);
        }
       
        this.GridView1.DataSource = dt.DefaultView;
        this.GridView1.DataBind();
    }

protected void GridView1_DataBound(object sender, EventArgs e)
    {
        //如果是空行,判断条件为:行数=1且主键列=DBNull.Value,如果需要区分是初始化/提交状态,可以加入 Page.IsPostBack 判断
        if (GridView1.DataKeys.Count == 1 && GridView1.DataKeys[0].Values[0] == DBNull.Value)
        {
            //清除掉该空行的全部单元格
            GridView1.Rows[0].Cells.Clear();
            //新建单元格对象
            TableCell cell = new TableCell();
            //合并单元格
            cell.ColumnSpan = GridView1.Columns.Count;

            this.GridView1.EmptyDataText = "没有查找到符合条件的记录";

            //设置单元格内容为GridView1.EmptyDataText,把提示文本给分离出来
            cell.Text = GridView1.EmptyDataText;
            //向空行中加入单元格
            GridView1.Rows[0].Cells.Add(cell);
            //让该行应用EmptyDataRowStyle样式,这样可以更加灵活,比如可以很容易的应用主题
            GridView1.Rows[0].ApplyStyle(GridView1.EmptyDataRowStyle);
        }
    }

注意:要设置GridView的DataKeyNames

 

posted on 2012-08-14 09:10  小黑混北京  阅读(648)  评论(0编辑  收藏  举报