问题
I have a gridview which gets populated in the backend code. I am trying to implement paging now, but when I am trying my way, I am getting nothing. Here is my piece of code:
public void generateTable()
{
conn.ConnectionString = connString;
SqlCommand comm = new SqlCommand("ViewBusinessInfo", conn);
comm.CommandType = CommandType.StoredProcedure;
comm.CommandTimeout = 2;
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (rdr.HasRows)
{
gvAssociation.DataSource = rdr;
gvAssociation.DataBind();
gvAssociation.AllowPaging = true;
gvAssociation.PageSize = 10;
rdr.Close();
}
else
{
lblResult.Text = "No businesses found.";
lblResult.Visible = true;
}
}
catch
{
}
finally
{
conn.Close();
}
}
Can anyone advice what am I doing wrong and I can't get the paging in the gridview? Thx in advance, Laziale
回答1:
You cannot use paging with a DataReader. You should fill your data into a Dataset or a Datatable using a DataAdapter. Something like this:
SqlCommand myCommand = new SqlCommand("ViewBusinessInfo", conn);
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand))
DataTable dt = new DataTable();
myAdapter.Fill(dt);
...
回答2:
The allowPaging and pagesize property of the gridview can be added in the .aspx, where the gridview tag is present.
<asp:GridView ID="gridView" OnPageIndexChanging="gridView_PageIndexChanging" AllowPaging="True" pagesize="10" runat="server" />
Additionally, to make the paging links work, you have to add the following code in the gridview_PageIndexChanging
event of the gridview:
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
gridView.DataBind();
}
Hope this is helpful.
回答3:
Set the AllowPaging
and PageSize
declaratively, or do so before you call DataBind()
.
来源:https://stackoverflow.com/questions/8215826/gridview-control-and-paging-asp-net