页面大小导致gridview DataBind错误

本文关键字:gridview DataBind 错误 | 更新日期: 2023-09-27 18:17:24

我正面临一个奇怪的问题,也许我正在做一个愚蠢的错误。我有一个包含五行的数据表。我正在创建一个gridview从代码背后。对于分页,如果我指定Page size =5(数据表的大小),一切都很好,但当我指定的页面大小小于数据表的大小,例如Page size=2,我得到:

对象引用未设置为对象的实例。

in gvEmployee.DataBind();

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace demogrid
{
    public partial class grid : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable table = new DataTable();
                table.Columns.Add("Dosage", typeof(int));
                table.Columns.Add("Drug", typeof(string));
                table.Columns.Add("Patient", typeof(string));
                table.Columns.Add("Date", typeof(DateTime));
                // Here we add five DataRows.
                table.Rows.Add(25, "Indocin", "David", DateTime.Now);
                table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
                table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
                table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
                table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
                BindData(table);
            }
        }
        protected void BindData(DataTable dt)
        {
            GridView gvEmployee = new GridView();
            gvEmployee.AllowPaging = true;
            gvEmployee.PageSize = 5;//getting error if the page size is less than 5
            gvEmployee.AutoGenerateColumns = false;
            if (dt != null)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    BoundField boundfield = new BoundField();
                    boundfield.DataField = dt.Columns[i].ColumnName.ToString();
                    boundfield.HeaderText = dt.Columns[i].ColumnName.ToString();
                    gvEmployee.Columns.Add(boundfield);
                }
                gvEmployee.DataSource = dt;
                gvEmployee.DataBind();
                gvEmployee.Width = 600;
                gvEmployee.HeaderStyle.CssClass = "header";
                gvEmployee.RowStyle.CssClass = "rowstyle";
                Panel1.Controls.Add(gvEmployee);
            }
        }
    }
}
异常堆栈

:

at System.Web.UI.WebControls.GridView.get_StateFormatter()
       at System.Web.UI.WebControls.GridView.BuildCallbackArgument(Int32 pageIndex)
       at System.Web.UI.WebControls.GridView.CreateNumericPager(TableRow row, PagedDataSource pagedDataSource, Boolean addFirstLastPageButtons)
       at System.Web.UI.WebControls.GridView.InitializePager(GridViewRow row, Int32 columnSpan, PagedDataSource pagedDataSource)
       at System.Web.UI.WebControls.GridView.CreateRow(Int32 rowIndex, Int32 dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState, Boolean dataBind, Object dataItem, DataControlField[] fields, TableRowCollection rows, PagedDataSource pagedDataSource)
       at System.Web.UI.WebControls.GridView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding)
       at System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data)
       at System.Web.UI.WebControls.GridView.PerformDataBinding(IEnumerable data)
       at System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data)
       at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback)
       at System.Web.UI.WebControls.DataBoundControl.PerformSelect()
       at System.Web.UI.WebControls.BaseDataBoundControl.DataBind()
       at System.Web.UI.WebControls.GridView.DataBind()
       at demogrid.grid.BindData(DataTable dt) in c:'Users'sample'Documents'Visual Studio 2012'Projects'demogrid'demogrid'grid.aspx.cs:line 59
       at demogrid.grid.Page_Load(Object sender, EventArgs e) in c:'Users'sample'Documents'Visual Studio 2012'Projects'demogrid'demogrid'grid.aspx.cs:line 32

如有任何帮助,不胜感激。

页面大小导致gridview DataBind错误


发生异常是因为你的GridView还不是PAGE上的控件,而你正在调用DataBind在对进行数据绑定之前,必须在页面上添加控件。
并且您必须实现PageIndexChanging Event来处理页面更改事件。

还有一件事是你需要从if (!IsPostBack)块中移动你的数据表代码,因为当页面POSTBACK和控件不再在页面上时,当页面被改变或任何POSTBACK事件被触发时,它不会被执行。这是一个工作代码。

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace demogrid
{
    public partial class grid : System.Web.UI.Page
    {
    GridView gvEmployee = new GridView();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
        }
        DataTable table = new DataTable();
        table.Columns.Add("Dosage", typeof(int));
        table.Columns.Add("Drug", typeof(string));
        table.Columns.Add("Patient", typeof(string));
        table.Columns.Add("Date", typeof(DateTime));
        // Here we add five DataRows.
        table.Rows.Add(25, "Indocin", "David", DateTime.Now);
        table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
        table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
        table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
        table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
        BindData(table);
    }
    protected void BindData(DataTable dt)
    {
        gvEmployee.AllowPaging = true;
        gvEmployee.PageSize = 2;
        gvEmployee.AutoGenerateColumns = false;
        gvEmployee.PageIndexChanging += gvEmployee_PageIndexChanging;
        if (dt != null)
        {
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                BoundField boundfield = new BoundField();
                boundfield.DataField = dt.Columns[i].ColumnName.ToString();
                boundfield.HeaderText = dt.Columns[i].ColumnName.ToString();
                gvEmployee.Columns.Add(boundfield);
            }
            Panel1.Controls.Add(gvEmployee);
            gvEmployee.DataSource = dt;
            gvEmployee.DataBind();
            gvEmployee.Width = 600;
            gvEmployee.HeaderStyle.CssClass = "header";
            gvEmployee.RowStyle.CssClass = "rowstyle";
        }
    }
    void gvEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvEmployee.PageIndex = e.NewPageIndex;
        gvEmployee.DataBind();
    }

}
}

这是因为没有Pager Template被设置为GridView。我已经修改了你的代码,让你开始。首先添加RowDataBound处理程序并设置分页:

    protected void BindData(DataTable dt)
    {
        GridView gvEmployee = new GridView();
        gvEmployee.AllowPaging = true;
        gvEmployee.PageSize = 4;//this Will work now
        gvEmployee.AutoGenerateColumns = false;
        if (dt != null)
        {
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                BoundField boundfield = new BoundField();
                boundfield.DataField = dt.Columns[i].ColumnName.ToString();
                boundfield.HeaderText = dt.Columns[i].ColumnName.ToString();
                gvEmployee.Columns.Add(boundfield);
            }
            gvEmployee.DataSource = dt;
            gvEmployee.RowDataBound += gvEmployee_RowDataBound;
            gvEmployee.PagerTemplate = new MyTemplate();
            gvEmployee.DataBind();
            gvEmployee.Width = 600;
            gvEmployee.HeaderStyle.CssClass = "header";
            gvEmployee.RowStyle.CssClass = "rowstyle";
            Panel1.Controls.Add(gvEmployee);
        }
    }
    void gvEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        switch (e.Row.RowType)
        {
            case DataControlRowType.DataRow:
                break;
            case DataControlRowType.EmptyDataRow:
                break;
            case DataControlRowType.Footer:
                break;
            case DataControlRowType.Header:
                break;
            case DataControlRowType.Pager:
                //TODO: handle your pager...
                break;
            case DataControlRowType.Separator:
                break;
            default:
                break;
        }
    }

这里是基本的寻呼机控制:

public class MyTemplate : WebControl, ITemplate
{
    public void InstantiateIn(Control container)
    {
        //TODO: create your pager controls...
    }
}