简体   繁体   中英

Binding data to gridview. How to use paging?

It is popping an exception saying I can not using paging on the server side.

conn.Open(); 
string querstring = "select * from gt_transaction_log where LogTimeStamp between '2013-09-19 07:06:00.077' and '2013-09-19 10:28:25.163' ";
SqlCommand cmd = new SqlCommand(querstring, conn);
GridView1.EmptyDataText = "no record found";
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();

GridView1.AllowPaging = true;
GridView1.PageSize = 5; 

You cannot use paging with a DataReader . So problem is with this line:

GridView1.DataSource = cmd.ExecuteReader();

You should fill GridView using a Dataset or a Datatable using a DataAdapter .

Example:

// Using DataTable

string querstring = "select * from gt_transaction_log where LogTimeStamp between
                     '2013-09-19 07:06:00.077' and '2013-09-19 10:28:25.163' ";
SqlDataAdapter adapter = new SqlDataAdapter(querstring , conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
GridView1.DataSource=dt;
GridView1.DataBind();

// Using DataSet

string querstring = "select * from gt_transaction_log where LogTimeStamp between
                     '2013-09-19 07:06:00.077' and '2013-09-19 10:28:25.163' ";
SqlDataAdapter adapter = new SqlDataAdapter(querstring , conn);
DataSet ds = new DataSet();
adapter.Fill(ds, "Table_Name"); // you can supply a table name
GridView1.DataSource=ds;
GridView1.DataBind();

You must specify if you want paging in the UI of the page, that is :

<asp:GridView ID="grid" runat="server" AllowPaging="true" PageSize="5" OnPageIndexChanging="grid_PageIndexChanging" />

Then in the cs file:

 protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            grid.PageIndex = e.NewPageIndex;
            BindGrid();
        }
        catch (Exception ex)
        {
        }
    }

Where BindGrid() method is the one in which we bind the grid.

在设计视图上,单击Gridview>允许分页或使用SQLdatasource,然后允许分页

You can try using this code.......

String constring = "Data Source=dsdsdsds;Initial Catalog=table;User Id=uid;Password=pass";
SqlConnection conqav = new SqlConnection(constring);
String takeffty = "select top 10 * from table";
conqav.Open();
SqlCommand comqav = new SqlCommand(takeffty,conqav);
GridView1.DataSource = comqav.ExecuteReader();
GridView1.DataBind();
conqav.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM