When building ASP.NET Web applications, one of the most common tasks is displaying data. ASP.NET offers a powerful data Web control - the DataList but imposes some limitations on its paging capabilities. Therefore, i am going to explain how to implement paging in DataList using ASP.NET.
aspx page
<form id="form1" runat="server">
<table>
<asp:DataList ID="dltItems" runat="server">
<HeaderTemplate>
<h2>Item Details </h2>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<h4>Price</h4>
</td>
<td>
<h4>Quantity</h4>
</td>
</tr>
<tr>
<td>
<h5><%#Eval("price") %></h5>
</td>
<td>
<h5><%#Eval("quantity") %></h5>
</td>
</tr>
</ItemTemplate>
</asp:DataList>
</table>
<table>
<tr>
<td>
<asp:Button ID="btnfirst" runat="server" Font-Bold="true" Text="<<" OnClick="btnfirst_Click" /></td>
<td>
<asp:Button ID="btnprevious" runat="server" Font-Bold="true" Text="<" OnClick="btnprevious_Click" /></td>
<td>
<asp:Button ID="btnnext" runat="server" Font-Bold="true" Text=">" OnClick="btnnext_Click" /></td>
<td>
<asp:Button ID="btnlast" runat="server" Font-Bold="true" Text=">>" OnClick="btnlast_Click" /></td>
</tr>
</table>
</form>
aspx.cs page
PagedDataSource pdsPaging = new PagedDataSource();
int startPosition;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["vspaging"] = 0;
}
startPosition = Convert.ToInt32(ViewState["vspaging"].ToString());
bindData();
}
void bindData()
{
string connectionString = "Server=localhost;Database=shopping;Trusted_Connection=true";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT price, quantity FROM demo", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
pdsPaging.DataSource = ds.Tables[0].DefaultView; //returns dataview
pdsPaging.PageSize = 4; // specify no. of rows bind at startup
pdsPaging.AllowPaging = true; // make it true to allow paging
pdsPaging.CurrentPageIndex = startPosition;
dltItems.DataSource = pdsPaging;
dltItems.DataBind(); // bind data in datalist
}
protected void btnfirst_Click(object sender, EventArgs e)
{
startPosition = 0; // set it zero to go to first page
bindData();
}
protected void btnprevious_Click(object sender, EventArgs e)
{
startPosition = Convert.ToInt32(ViewState["vspaging"].ToString());
startPosition -= 1; // subtract one from actual postion
ViewState["vspaging"] = startPosition; // set new value in viewstate
bindData();
}
protected void btnnext_Click(object sender, EventArgs e)
{
startPosition = Convert.ToInt32(ViewState["vspaging"].ToString());
startPosition += 1; // add one in actual postion
ViewState["vspaging"] = startPosition; // set new value in viewstate
bindData();
}
protected void btnlast_Click(object sender, EventArgs e)
{
// subtract one from no. of total pages because index starts from zero
startPosition = pdsPaging.PageCount - 1;
bindData();
}
Paging Output
That’s it!!…..Happy Programming...
No comments:
Post a Comment