Introduction
This article will give you knowledge how can implement Pagin in Datalist. Generally we are using pagin in Gridview and sometimes we need to use pagin in datalist. As in datalist we can define column horizontally or vertically as well. So its really amaging control. Now when we need to allow pagin we have to specify some code written by us, as Datalist does not have any event for pagin. So have a fun with code.
Using the code
Use below code in your codebehind file.
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
TextBox1.Text="0";
TextBox2.Text="1";
Build_List();
}
}
private void Build_List()
{
try
{
SqlConnection con;
SqlDataAdapter adp;
con = new SqlConnection("Connection String");
con.Open();
adp = new SqlDataAdapter("Command String", con);
DataSet ods = new DataSet();
int index = int.Parse(TextBox1.Text);
adp.Fill(ods, index, 1, "contact");
DataList1.DataSource=ods.Tables["contact"].DefaultView;
HiddenField1.Value = ods.Tables["contact"].Rows.Count.ToString();
DataList1.DataBind();
con.Close();
}
catch(Exception ex)
{
Response.Write(ex.Message+" "+ex.StackTrace);
}
}
private void LinkButton1_Click(object sender, System.EventArgs e)
{
int index = int.Parse(TextBox1.Text);
if(index >0)
{
index--;
TextBox1.Text= index.ToString();
Build_List();
}
}
private void LinkButton2_Click(object sender, System.EventArgs e)
{
int index = int.Parse(TextBox1.Text);
if(Convert.ToInt32( HiddenField1.Value) >= index)
{
index++;
TextBox1.Text= index.ToString();
Build_List();
}
}
<HTML>
<HEAD>
<title>Paging in Datalist</title>
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<table border="1" style="width: 300px">
<TBODY>
<tr>
<td><asp:DataList id="DataList1" runat="server" Visible="True">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
Message :
<%# DataBinder.Eval(Container.DataItem, "Mess")%>
<br>
From User :
<%# DataBinder.Eval(Container.DataItem, "FromUser")%>
<br>
User Name :
<%# DataBinder.Eval(Container.DataItem, "userName")%>
<br>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:DataList></td>
</tr>
<tr>
<td><asp:LinkButton id="LinkButton1" runat="server">Prev</asp:LinkButton>
<asp:LinkButton id="LinkButton2" runat="server">Next</asp:LinkButton></td>
</tr>
<tr>
<td><asp:TextBox id="TextBox1" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:TextBox id="TextBox2" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td></td>
</tr>
</TBODY>
</table>
<asp:HiddenField ID="HiddenField1" runat="server" />
</form>
</body>
</HTML>
Points of Interest
Best of luck guys... :)
Working as a Team Lead in MNC located at India.
In IT world, I have worked with Microsoft Technologies and always ready for R&D.
Worked with Website Development and Windows based applications as well.
New errors are really good and being happy to resolve those.....