Thursday 9 June 2016


In this tutorial I will explain how to Implement Custom Attractive Pagination In Repeater Control In Asp.net tips & guide.

Description:
By default Repeater control does not have pagination option. To implement the pagination in Repeater we have to write the custom code for it.
In this tutorial I am using two repeater control (one to bind the data and 2nd one to display page number) and 4 link buttons (to go page First, Last, Next and Previous page). On page load only 4 page numbers will be visible when user clicks on page number 4 next page numbers will be display and so on.

Implementation:-
Drag and drop the required controls from toolbox to webform. Add the given style in head section of webform.
     <style>
        .btncss
         {
padding:8px;
margin:2px;
background:#ffa100;
border:solid 1px #666;
font:8pt tahoma;
font-weight:bold;
color:#000;
        }
        table tr td
       {
           text-align:center;
          margin:5px;
           }
       table tr th
       {
            margin:5px;
            padding:5px;
           }
    </style>
Complete HTML markup of Webform:-

C#:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
        <style>
        .btncss
         {
padding:8px;
margin:2px;
background:#ffa100;
border:solid 1px #666;
font:8pt tahoma;
font-weight:bold;
color:#000;
        }
        table tr td
       {
           text-align:center;
          margin:5px;
           }
       table tr th
       {
            margin:5px;
            padding:5px;
           }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
        <tr><td>
            <asp:Repeater ID="rptsudentdetail" runat="server">
                <HeaderTemplate>
                    <table>
                          <thead>
            <tr>
                <th><b>Student Name</b> </th>
              <th>Fee</th>
                <th>Class </th>
                <th>Roll No.</th>
             </tr>
               </thead>
                </HeaderTemplate>
                <ItemTemplate>
                 <tr><td><%#DataBinder.Eval(Container, "DataItem.SudentName")%></td>
                     <td><%#DataBinder.Eval(Container, "DataItem.Fee")%></td>
                     <td><%#DataBinder.Eval(Container, "DataItem.StudentClass")%></td>
                     <td><%#DataBinder.Eval(Container, "DataItem.StudentRollNo")%></td>
                 </tr>
                </ItemTemplate>
            </asp:Repeater>
        </td></tr>
        <tr><td colspan="4"></td></tr>
        <tr><td></td></tr>
    </table>
        <table style="text-align:center;">
          <tr> <td>  <asp:LinkButton ID="lnkFirst" runat="server" CssClass="btncss"> << First</asp:LinkButton></td>
              <td> <asp:LinkButton ID="lnkPrevious" runat="server" CssClass="btncss"> < Previous </asp:LinkButton></td>
               <td><asp:Repeater ID="repeaterpaging" runat="server">
                         <ItemTemplate>
                                <asp:LinkButton ID="btnPage" CssClass="btncss"
                CommandName="Page" CommandArgument='<%# Eval("PageIndex") %>'
                                        Text='<%# Eval("PageText") %> '
                 runat="server" Font-Bold="True">
                                </asp:LinkButton>                           
           </ItemTemplate>
        </asp:Repeater></td>
             <td>  <asp:LinkButton ID="lnkNext" runat="server" CssClass="btncss">Next > </asp:LinkButton></td>
              <td><asp:LinkButton ID="lnkLast" runat="server" CssClass="btncss">Last >> </asp:LinkButton></td>
          </tr>
                </table>
    </div>
    </form>
</body>
</html>

VB:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
        <style>
        .btncss
         {
padding:8px;
margin:2px;
background:#ffa100;
border:solid 1px #666;
font:8pt tahoma;
font-weight:bold;
color:#000;
        }
        table tr td
       {
           text-align:center;
          margin:5px;
           }
       table tr th
       {
            margin:5px;
            padding:5px;
           }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
        <tr><td>
            <asp:Repeater ID="rptsudentdetail" runat="server">
                <HeaderTemplate>
                    <table>
                          <thead>
            <tr>
                <th><b>Student Name</b> </th>
              <th>Fee</th>
                <th>Class </th>
                <th>Roll No.</th>
             </tr>
               </thead>
                </HeaderTemplate>
                <ItemTemplate>
                 <tr><td><%#DataBinder.Eval(Container, "DataItem.SudentName")%></td>
                     <td><%#DataBinder.Eval(Container, "DataItem.Fee")%></td>
                     <td><%#DataBinder.Eval(Container, "DataItem.StudentClass")%></td>
                     <td><%#DataBinder.Eval(Container, "DataItem.StudentRollNo")%></td>
                 </tr>
                </ItemTemplate>
            </asp:Repeater>
        </td></tr>
        <tr><td colspan="4"></td></tr>
        <tr><td></td></tr>
    </table>
        <table style="text-align:center;">
          <tr> <td>  <asp:LinkButton ID="lnkFirst" runat="server" CssClass="btncss"> << First</asp:LinkButton></td>
              <td> <asp:LinkButton ID="lnkPrevious" runat="server" CssClass="btncss"> < Previous </asp:LinkButton></td>
               <td><asp:Repeater ID="repeaterpaging" runat="server">
                         <ItemTemplate>
                                <asp:LinkButton ID="btnPage" CssClass="btncss"
                CommandName="Page" CommandArgument='<%# Eval("PageIndex") %>'
                                        Text='<%# Eval("PageText") %> '
                 runat="server" Font-Bold="True">
                                </asp:LinkButton>                           
           </ItemTemplate>
        </asp:Repeater></td>
             <td>  <asp:LinkButton ID="lnkNext" runat="server" CssClass="btncss">Next > </asp:LinkButton></td>
              <td><asp:LinkButton ID="lnkLast" runat="server" CssClass="btncss">Last >> </asp:LinkButton></td>
          </tr>
                </table>
    </div>
    </form>
</body>
</html>

After design the webform. Now move to code file.

Add the namespace
C#:-
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
VB:-
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Collections

Create connection
C#:-
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
VB:-
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())

Write the code to bind the repeater and do pagination.
C#:-
  public static int totalPages = 0;
  int FirstIndex, LastIndex;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindRepeater();
        }
    }
    public int Pageno
    {
        get
        {
            if (ViewState["pagenumber"] != null)
                return Convert.ToInt32(ViewState["pagenumber"]);
            else
                return 0;
        }
        set
        {
            ViewState["pagenumber"] = value;
        }
    }
    public void BindRepeater()
    {
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("Select * from Student_Detail", con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            PagedDataSource pagedatasource = new PagedDataSource();
            DataView dv = new DataView(dt);
            pagedatasource.DataSource = dv;
            pagedatasource.AllowPaging = true;
            pagedatasource.PageSize = 2;
            pagedatasource.CurrentPageIndex = Pageno;
            totalPages = pagedatasource.PageCount - 1;
            lnkPrevious.Enabled = !pagedatasource.IsFirstPage;
            lnkNext.Enabled = !pagedatasource.IsLastPage;
            lnkFirst.Enabled = !pagedatasource.IsFirstPage;
            lnkLast.Enabled = !pagedatasource.IsLastPage;
            ViewState["totpage"] = pagedatasource.PageCount;
            if (pagedatasource.PageCount > 1)
            {
                rptsudentdetail.DataSource = pagedatasource;
                rptsudentdetail.DataBind();
                DataTable dtnew = new DataTable();
                dtnew.Columns.Add("PageIndex");
                dtnew.Columns.Add("PageText");
                FirstIndex = Pageno - 2;
                if (Pageno > 2)
                {
                    LastIndex = Pageno + 2;
                }
                else
                {
                    LastIndex = 4;
                }
                if (LastIndex > Convert.ToInt32(ViewState["totpage"]))
                {
                    LastIndex = Convert.ToInt32(ViewState["totpage"]);
                    FirstIndex = LastIndex - 4;
                }
                if (FirstIndex < 0)
                {
                    FirstIndex = 0;
                }
                 for (int i = FirstIndex; i < LastIndex; i++)
                {
                    DataRow dr = dtnew.NewRow();
                    dr[0] = i;
                    dr[1] = i + 1;
                    dtnew.Rows.Add(dr);
                }
                repeaterpaging.DataSource = dtnew;
                repeaterpaging.DataBind();               
            }         
        }
        catch (Exception ex)
        {
        }
    }

VB:-
Public Shared totalPages As Integer = 0
Dim FirstIndex As Integer, LastIndex As Integer
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindRepeater()
        End If
    End Sub
    Public Property Pageno() As Integer
        Get
            If ViewState("pagenumber") IsNot Nothing Then
                Return Convert.ToInt32(ViewState("pagenumber"))
            Else
                Return 0
            End If
        End Get
        Set(value As Integer)
            ViewState("pagenumber") = value
        End Set
    End Property
    Public Sub BindRepeater()
        Try
            Dim adp As New SqlDataAdapter("Select * from Student_Detail", con)
            Dim dt As New DataTable()
            adp.Fill(dt)
            Dim pagedatasource As New PagedDataSource()
            Dim dv As New DataView(dt)
            pagedatasource.DataSource = dv
            pagedatasource.AllowPaging = True
            pagedatasource.PageSize = 2
            pagedatasource.CurrentPageIndex = Pageno
            totalPages = pagedatasource.PageCount - 1
            lnkPrevious.Enabled = Not pagedatasource.IsFirstPage
            lnkNext.Enabled = Not pagedatasource.IsLastPage
            lnkFirst.Enabled = Not pagedatasource.IsFirstPage
            lnkLast.Enabled = Not pagedatasource.IsLastPage
            ViewState("totpage") = pagedatasource.PageCount
            If pagedatasource.PageCount > 1 Then
                rptsudentdetail.DataSource = pagedatasource
                rptsudentdetail.DataBind()
                Dim dtnew As New DataTable()
                dtnew.Columns.Add("PageIndex")
                dtnew.Columns.Add("PageText")
                FirstIndex = Pageno - 2
                If Pageno > 2 Then
                    LastIndex = Pageno + 2
                Else
                    LastIndex = 4
                End If
                If LastIndex > Convert.ToInt32(ViewState("totpage")) Then
                    LastIndex = Convert.ToInt32(ViewState("totpage"))
                    FirstIndex = LastIndex - 4
                End If
                If FirstIndex < 0 Then
                    FirstIndex = 0
                End If
                For i As Integer = FirstIndex To LastIndex - 1
                    Dim dr As DataRow = dtnew.NewRow()
                    dr(0) = i
                    dr(1) = i + 1
                    dtnew.Rows.Add(dr)
                Next
                repeaterpaging.DataSource = dtnew
                repeaterpaging.DataBind()
            End If
        Catch ex As Exception
        End Try
    End Sub

Now write the code on link button click to move first, last, next and previous page number.
C#:-
protected void lnkFirst_Click(object sender, EventArgs e)
    {
        lnkFirst.Attributes["style"] = "background-color:black;color:#fff";
        lnkPrevious.Attributes["style"] = "";
        lnkLast.Attributes["style"] = "";
        lnkNext.Attributes["style"] = "";
        Pageno = 0;
        BindRepeater();
    }
    protected void lnkPrevious_Click(object sender, EventArgs e)
    {
        lnkPrevious.Attributes["style"] = "background-color:black;color:#fff";
        lnkFirst.Attributes["style"] = "";
        lnkLast.Attributes["style"] = "";
        lnkNext.Attributes["style"] = "";
        if (Pageno == 0)
        {
            Pageno = 0;
        }
        else
        {
            Pageno = Pageno - 1;
        }
        BindRepeater();
    }
    protected void lnkNext_Click(object sender, EventArgs e)
    {
        lnkNext.Attributes["style"] = "background-color:black;color:#fff";
        lnkFirst.Attributes["style"] = "";
        lnkPrevious.Attributes["style"] = "";
        lnkLast.Attributes["style"] = "";
        if (Pageno == totalPages)
        {
            Pageno = totalPages;
        }
        else
        {
            Pageno = Pageno + 1;
        }
        BindRepeater();
    }
    protected void lnkLast_Click(object sender, EventArgs e)
    {
        lnkLast.Attributes["style"] = "background-color:black;color:#fff";
        lnkFirst.Attributes["style"] = "";
        lnkPrevious.Attributes["style"] = "";
        lnkNext.Attributes["style"] = "";
        Pageno = (Convert.ToInt32(ViewState["totpage"]) - 1);
        BindRepeater();
    }

VB:-
Protected Sub lnkFirst_Click(sender As Object, e As EventArgs) Handles lnkFirst.Click
        lnkFirst.Attributes("style") = "background-color:black;color:#fff"
        lnkPrevious.Attributes("style") = ""
        lnkLast.Attributes("style") = ""
        lnkNext.Attributes("style") = ""
        Pageno = 0
        BindRepeater()
    End Sub
    Protected Sub lnkPrevious_Click(sender As Object, e As EventArgs) Handles lnkPrevious.Click
        lnkPrevious.Attributes("style") = "background-color:black;color:#fff"
        lnkFirst.Attributes("style") = ""
        lnkLast.Attributes("style") = ""
        lnkNext.Attributes("style") = ""
        If Pageno = 0 Then
            Pageno = 0
        Else
            Pageno = Pageno - 1
        End If
        BindRepeater()
    End Sub
    Protected Sub lnkNext_Click(sender As Object, e As EventArgs) Handles lnkNext.Click
        lnkNext.Attributes("style") = "background-color:black;color:#fff"
        lnkFirst.Attributes("style") = ""
        lnkPrevious.Attributes("style") = ""
        lnkLast.Attributes("style") = ""
        If Pageno = totalPages Then
            Pageno = totalPages
        Else
            Pageno = Pageno + 1
        End If
        BindRepeater()
    End Sub
    Protected Sub lnkLast_Click(sender As Object, e As EventArgs) Handles lnkLast.Click
        lnkLast.Attributes("style") = "background-color:black;color:#fff"
        lnkFirst.Attributes("style") = ""
        lnkPrevious.Attributes("style") = ""
        lnkNext.Attributes("style") = ""
        Pageno = (Convert.ToInt32(ViewState("totpage")) - 1)
        BindRepeater()
    End Sub

After that write the code on Repeater control events (ItemCommand, ItemDataBound) which we are using for paging.     
C#:-
protected void repeaterpaging_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        Pageno = Convert.ToInt32(e.CommandArgument.ToString());
        BindRepeater();
    }
    protected void repeaterpaging_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        LinkButton lnk = (LinkButton)e.Item.FindControl("btnPage");
        if (lnk.CommandArgument.ToString() == (Pageno).ToString())
        {
            lnk.ForeColor = System.Drawing.Color.Black;
        }
        else
        {
            {
                lnk.ForeColor = System.Drawing.Color.White;
            }
        } 
    }

VB:-
Protected Sub repeaterpaging_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles repeaterpaging.ItemDataBound
        Dim lnk As LinkButton = DirectCast(e.Item.FindControl("btnPage"), LinkButton)
        If lnk.CommandArgument.ToString() = (Pageno).ToString() Then
            lnk.ForeColor = System.Drawing.Color.Black
        Else
            If True Then
                lnk.ForeColor = System.Drawing.Color.White
            End If
        End If
    End Sub
    Protected Sub repeaterpaging_ItemCommand(source As Object, e As RepeaterCommandEventArgs) Handles repeaterpaging.ItemCommand
        Pageno = Convert.ToInt32(e.CommandArgument.ToString())
        BindRepeater()
    End Sub

Build, run the project and see the result.
 Result:
Implement Custom Attractive Pagination in Repeater Control in Asp.net Tips & Guide


Thursday 26 May 2016

Load the popup on just the first time page request only


protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            ClientScript.RegisterHiddenField("isPostBack", "1");
        }
}
<script type="text/javascript" >

        $(document).ready(function() {

            var isPostBackObject = document.getElementById('isPostBack');
            if (isPostBackObject == null) {
                var id = '#dialog';
                //modal: true
                //Get the screen height and width
                var maskHeight = $(document).height();
                var maskWidth = $(window).width();

                //Set heigth and width to mask to fill up the whole screen
                $('#mask').css({ 'width': maskWidth, 'height': maskHeight });

                //transition effect  
                $('#mask').fadeIn(1000);
                $('#mask').fadeTo("slow", 0.9);

                //Get the window height and width
                var winH = $(window).height();
                var winW = $(window).width();

                //Set the popup window to center
                $(id).css('top', winH / 2 - $(id).height() / 2);
                $(id).css('left', winW / 2 - $(id).width() / 2);

                //transition effect
                $(id).fadeIn(2000);

                //if close button is clicked
                $('.window .close').click(function(e) {
                    //Cancel the link behavior
                    e.preventDefault();

                    $('#mask').hide();
                    $('.window').hide();
                });

            }
<style type="text/css">
  #mask {
  position:absolute;
  padding-left:60px;
  padding-top:80px;
  padding-bottom:80px;
  padding-right:50px; /*-- These Padding is for the border of jquery Pop-up --*/
  left:0;
  top:0;
  z-index:9999;
  background-color:#000000;
  display:none;
}  
#boxes .window {
  position:absolute;
  left:0;
  top:0;
  width:330px;
  height:147px;
  display:none;
  z-index:9999;
  padding:20px;
  background-color:#000000;  
  border: 20px solid #79BBFD;  
  border-radius: 10px;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;

}
#boxes #dialog {
  padding:10px;
  background:url('images/localOffers-bg.jpg'); 
  width:330px; height:147px; 
  background-repeat:no-repeat; 
  margin-top:20px;
  
}

<div id="boxes">
<div id="mask" >
<div id="dialog" class="window">
<span class="LocalOffersHeading">Find Local Offers                                     
<a href="#"  style="float: right; margin: -45px -45px 0 0;"  class="close"> 
<img src="Images/close_pop.png" alt="CLOSE" /></a> </span> <br /> <br />
Finding local offers has never been easier. Just select your city location from
the drop down and find the most recent local discounts in your area. We've also
made simple to stay in touch with you favorite merchants but signing up for the
email discounts! <br /><br />
<asp:DropDownList ID="ddlj" runat="server"  style="Width:228px;  Height:20px;" 
 OnSelectedIndexChanged="popup_SelectedIndexChanged" >
</asp:DropDownList>
                                     
<asp:ImageButton ID="jqbutton" runat="server" ImageUrl="~/images/bt-go.jpg"
 OnClick="imgBtnGo_Click"
 CausesValidation="false" Style="height: 16px;"  />
                                       
</div>
<!-- Mask to cover the whole screen -->
<%--<div style="width: 1478px; height: 602px; display: none; opacity: 0.8;" id="mask">
</div>--%>
                                </div>
                            </div>

How to send email Asynchronously in ASP.Net using Background Thread

HTML Markup

<table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td style="width: 80px">
            To:
        </td>
        <td>
            <asp:TextBox ID="txtTo" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Subject:
        </td>
        <td>
            <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td valign = "top">
            Body:
        </td>
        <td>
            <asp:TextBox ID="txtBody" runat="server" TextMode = "MultiLine" Height = "150" Width = "200"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            File Attachment:
        </td>
        <td>
            <asp:FileUpload ID="fuAttachment" runat="server" />
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Gmail Email:
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Gmail Password:
        </td>
        <td>
            <asp:TextBox ID="txtPassword" runat="server" TextMode = "Password"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
        </td>
        <td>
            <asp:Button Text="Send" OnClick="SendAsyncEmail" runat="server" />
        </td>
    </tr>
</table>



Namespaces
You will need to import the following namespaces
C#

using System.IO;
using System.Net;
using System.Net.Mail;
using System.Threading;

VB.Net

Imports System.IO
Imports System.Net
Imports System.Net.Mail
Imports System.Threading


Sending email asynchronously in background using Thread


C#

protected void SendAsyncEmail(object sender, EventArgs e)
{
    string to = txtTo.Text;
    string from = txtEmail.Text;
    string password = txtPassword.Text;
    string subject = txtSubject.Text;
    string body = txtBody.Text;
    HttpPostedFile postedFile = fuAttachment.PostedFile;
    Thread email = new Thread(delegate()
    {
        SendEmail(to, from, password, subject, body, postedFile);
    });
 
    email.IsBackground = true;
    email.Start();
    ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
}
 
private void SendEmail(string to, string from, string password, string subject, string body, HttpPostedFile postedFile)
{
    using (MailMessage mm = new MailMessage(from, to))
    {
        mm.Subject = subject;
        mm.Body = body;
        if (postedFile.ContentLength > 0)
        {
            string fileName = Path.GetFileName(postedFile.FileName);
            mm.Attachments.Add(new Attachment(postedFile.InputStream, fileName));
        }
        mm.IsBodyHtml = false;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        NetworkCredential NetworkCred = new NetworkCredential(from, password);
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
    }
}

VB.Net

Protected Sub SendAsyncEmail(sender As Object, e As EventArgs)
    Dim [to] As String = txtTo.Text
    Dim from As String = txtEmail.Text
    Dim password As String = txtPassword.Text
    Dim subject As String = txtSubject.Text
    Dim body As String = txtBody.Text
    Dim postedFile As HttpPostedFile = fuAttachment.PostedFile
    Dim email As New Thread(Sub() SendEmail([to], from, password, subject, body, postedFile))
    email.IsBackground = True
    email.Start()
    ClientScript.RegisterStartupScript([GetType](), "alert", "alert('Email sent.');", True)
End Sub
 
Private Sub SendEmail([to] As String, from As String, password As String, subject As String, body As String, postedFile As HttpPostedFile)
    Using mm As New MailMessage(from, [to])
        mm.Subject = subject
        mm.Body = body
        If postedFile.ContentLength > 0 Then
            Dim fileName As String = Path.GetFileName(postedFile.FileName)
            mm.Attachments.Add(New Attachment(postedFile.InputStream, fileName))
        End If
        mm.IsBodyHtml = False
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.gmail.com"
        smtp.EnableSsl = True
        Dim NetworkCred As New NetworkCredential(from, password)
        smtp.UseDefaultCredentials = True
        smtp.Credentials = NetworkCred
        smtp.Port = 587
        smtp.Send(mm)
    End Using
End Sub