Friday, 9 December 2016

Find Control of aspcontrol in ItemTeplate using datakeyfield in DataList Control

 LinkButton lnkbtn = sender as LinkButton;
        DataListItem itm = lnkbtn.NamingContainer as DataListItem;
 lblID.Text = Convert.ToString(DataListBalsabha.DataKeys[itm.ItemIndex].ToString());

How to Use Cookies in Asp.net


Cookies in ASP.NET

Introduction

Cookies are also known by many names, HTTP Cookie, Web Cookie, Browser Cookie, Session Cookie, etc. Cookies are one of several ways to store data about web site visitors during the time when web server and browser are not connected. Common use of cookies is to remember users between visits. Practically, cookie is a small text file sent by web server and saved by web browser on client machine.

Use of Cookies?

Cookies may be used for authentication, identification of a user session, user's preferences, shopping cart contents, or anything else that can be accomplished through storing text data. Cookies can also be used for travelling of data from one page to another.

Is Cookies Secured?

Well, this question has no specific answers in YES or NO. Cookies could be stolen by hackers to gain access to a victim's web account. Even cookies are not software and they cannot be programmed like normal executable applications. Cookies cannot carry viruses and cannot install malware on the host computer. However, they can be used by spyware to track user's browsing activities.

Using Cookies

Creating/Writing Cookies

There are many ways to create cookies, I am going to outline some of them below:

Way 1 (by using HttpCookies class)

//First 
 
 WayHttpCookie StudentCookies = new HttpCookie("StudentCookies");
 StudentCookies.Value = TextBox1.Text;
 StudentCookies.Expires = DateTime.Now.AddHours(1);
 Response.Cookies.Add(StudentCookies);

Way 2 (by using Response directly)

//Second 
 
 WayResponse.Cookies["StudentCookies"].Value = TextBox1.Text;
 Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);

Way 3 (multiple values in same cookie)

//Writing Multiple values in single 
 cookieResponse.Cookies["StudentCookies"]["RollNumber"] = TextBox1.Text;
 Response.Cookies["StudentCookies"]["FirstName"] = "Avinash";
 Response.Cookies["StudentCookies"]["MiddleName"] = "Kumar";
 Response.Cookies["StudentCookies"]["LastName"] = "Vatsa";
 Response.Cookies["StudentCookies"]["TotalMarks"] = "499";
 Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1); 

Reading/Getting Cookies

In the above code, I have used many ways to write or create cookies so I need to write here using all the above ways separately.

For Way 1

string roll = Request.Cookies["StudentCookies"].Value; //For First Way

For Way 2

string roll = Request.Cookies["StudentCookies"].Value;  //For Second Way

For Way 3

//For Multiple values in single cookiestring roll;
roll = Request.Cookies["StudentCookies"]["RollNumber"];
 roll = roll   " "   Request.Cookies["StudentCookies"]["FirstName"];
 roll = roll   " "   Request.Cookies["StudentCookies"]["MiddleName"];
 roll = roll   " "   Request.Cookies["StudentCookies"]["LastName"];
 roll = roll   " "   Request.Cookies["StudentCookies"]["TotalMarks"];
 Label1.Text = roll; 

Deleting Cookies

In the above code, I have used many ways to create or read cookies. Now look at the code given below which will delete cookies.
if (Request.Cookies["StudentCookies"] != null)
    Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(-1); 
    Response.Redirect("Result.aspx");  //to refresh the page
 }

Understanding HttpCookie Class It contains a collection of all cookie values.

We do not need to use any extra namespaces for HttpCookies class (we already have used this in Way 1 above), because this class is derived from System.Web namespaces. HttpCookies class lets us work with cookies without using Response and Request objects (we have already used this in Way 2 and Way 3 above).
HttpCookie class has a list of some properties, let us outline them.
  • Domain: It contains the domain of the cookie.
  • Expires: It contains the expiration time of the cookie.
  • HasKeys: It contains True if the cookie has subkeys.
  • Name: It contains the name of the cookie.
  • Path: It contains the virtual path to submit with the cookie.
  • Secure: It contains True if the cookie is to be passed in a secure connection only.
  • Value: It contains the value of the cookie.
  • Values:
Limitations of Cookies
There are following limitations for cookies:
  1. Size of cookies is limited to 4096 bytes.
  2. Total 20 cookies can be used on a single website; if you exceed this browser will delete older cookies.
  3. End user can stop accepting cookies by browsers, so it is recommended to check the users’ state and prompt the user to enable cookies.
Sometimes, the end user disables the cookies on browser and sometimes browser has no such feature to accept cookies. In such cases, you need to check the users’ browser at the home page of website and display the appropriate message or redirect on appropriate page having such message to enable it first. The following code will check whether the users’ browser supports cookies or not. It will also detect if it is disabled too.
protected void Page_Load(object sender, EventArgs e)
 {   
  if (Request.Browser.Cookies)   
  { 
     //supports the cookies 
  }   
  else 
  {        
    // not supports the cookies
    // redirect user on specific page    
    // for this or show messages   

  }
 }
It is always recommended not to store sensitive information in cookies.
Download the sample code attached with this post to check it yourself.
So, that is all about the ASP.NET cookies. Please post your feedback.

 Create and Retrieve Cookies

public void create_retreive_Cookies()

    {

        //Find Clilent IP Address

        string VisitorsIPAddr = string.Empty;
        if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
        {
            VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
        }

        //Retrieve save cookies from computer
        HttpCookie FrisskaCartCookies = Request.Cookies["FrisskaCart"];

        //Check whether cookie exist or not
        if (FrisskaCartCookies == null)
        {
             //if cookeis doesnot exist then write new cookie
            string comname = "";
            FrisskaCartCookies = new HttpCookie("FrisskaCart");
            comname = Guid.NewGuid().ToString().GetHashCode().ToString("x"); ;
            ipaddress=VisitorsIPAddr "_" comname;
            FrisskaCartCookies["MacAddress"] = ipaddress;
            Response.Cookies.Add(FrisskaCartCookies);
            FrisskaCartCookies.Expires = DateTime.Now.AddMonths(1);
            Label2.Text = "New Cookies Written: " ipaddress;
         
        }
        else
        {          
             // if cookie exist then retrieve cookie value.  
            ipaddress = Request.Cookies["FrisskaCart"]["MacAddress"].ToString();
            Label2.Text = "Cookies Already Exist: " ipaddress;
        }    
       
    }

Excel connection string

FileUpload1.SaveAs(fileLocation);

     //Check whether file extension is xls or xslx

        if (fileExtension == ".xls")
     {
          connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" fileLocation ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
       }
          else if (fileExtension == ".xlsx")
        {
            connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" fileLocation ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
           }

Upload / Import excel with bulk import

Drag a button control in aspx page and find it button_click event and write these code inside
protected void Button1_Click(object sender, EventArgs e)
    {string path = string.Concat((Server.MapPath("~/temp/" FileUpload1.FileName)));
            FileUpload1.PostedFile.SaveAs(path);
            OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.Ace.OLEDB.12.0; Data Source =" path "; Extended Properties=Excel 12.0;");
            OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", OleDbcon);
            OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);

            OleDbcon.Open();
            OleDbDataReader dr = cmd.ExecuteReader();
            // SqlConnection con =new  SqlConnection(connection.cstr);
            SqlConnection con = new SqlConnection(connection.cstr);
            con.Open();
           // string con_str = @"Data Source=SANDEEP-PC\\SQLEXPRESS;Initial Catalog=Tmndx;Integrated Security=True";
            SqlBulkCopy bulkInsert = new SqlBulkCopy(con);
            bulkInsert.DestinationTableName = "country_code";
            bulkInsert.WriteToServer(dr);
            OleDbcon.Close();

            Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete);
            Label1.ForeColor = Color.Green;
            Label1.Text = "Successfully Inserted";
        }
        else
        {
            Label1.ForeColor = Color.Red;
            Label1.Text = "Please Select the File";
        }
    }

Popup form using Ajax Model Pop Up Extender in Ap.net C#

<asp:Button ID="btnShowPopup" runat="server" Style="display: none" />
            <asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="btnShowPopup"
                PopupControlID="pnlpopup" CancelControlID="btnCancel" BackgroundCssClass="modalBackground">
            </asp:ModalPopupExtender>
            <asp:Panel ID="pnlpopup" runat="server" BackColor="White" Height="300px" Width="400px"
                Style="display: none">
                <table width="100%" style="border: Solid 3px #D55500; width: 100%; height: 100%"
                    cellpadding="0" cellspacing="0">
                    <tr style="background-color: #D55500">
                        <td colspan="2" style="height: 10%; color: White; font-weight: bold; font-size: larger"
                            align="center">
                            Pay EMI
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 45%">
                            EMI ID:
                        </td>
                        <td>
                            <asp:Label ID="lblID" runat="server"></asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 45%">
                            Buyer Name:
                        </td>
                        <td>
                            <asp:Label ID="lblbuyername" runat="server"></asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            EMI No:
                        </td>
                        <td>
                            <asp:Label ID="lblemino" runat="server"></asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            EMI Amount:
                        </td>
                        <td>
                            <asp:Label ID="lblamount" runat="server"></asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            Payment Date:
                        </td>
                        <td>
                            <asp:TextBox ID="txtpaiddate" runat="server" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                        <td>
                            <asp:Button ID="btnUpdate" CommandName="Update" runat="server" Text="Pay" OnClick="btnUpdate_Click" />
                            <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
                        </td>
                    </tr>
                </table>
            </asp:Panel>



in code behind button event on which pop has to be displayed

protected void LinkButton3_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = sender as LinkButton;
        GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;               
        this.ModalPopupExtender1.Show();      
    }

Formatting asp.net label when the value is sourced from a query string

lbltotalamount.Text = String.Format("{0:N0}", int.Parse(Request.QueryString["tp"])); 

url routing in VS 2010 for asp.net c#


Step 1: work only on VS2010 and above

 In order to implement URL Routing we will need to register the routes that we need to use in our application.
In order to do that I have created a method named RegisterRoutes and it has been called inside the Application_Start event inside the Global.asax file. This method will allow us to add routes to handle so that we can create our own custom URLs.

<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web.Routing" %>

<script runat="server">
    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(System.Web.RouteTable.Routes);
    }
  
    static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapPageRoute("Customers", "Customers", "~/Customers.aspx");
    }
</script>

for more info visit.

Wednesday, 30 November 2016

Show Image Loader while processing data in Asp.net C# using Ajax UpdatePanel Animation Extender and JavaScript

<script type="text/javascript">
     function InProgress() {
         var panelProg = $get('divProgress');
         panelProg.style.display = '';

         var lbl = $get('<%# this.lblText.ClientID %>');
         lbl.innerHTML = '';
     }

     function onComplete() {
         var panelProg = $get('divProgress');
         panelProg.style.display = 'none';
     }     
    </script>
    <style type="text/css">
        .popup
        {
            border: 0px solid #6b6a63;
            width: 100%;
            height: 100%;
            position: fixed;
            background-color: rgba(0, 0, 0, .1);
            z-index: 99999;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
        }
        .prgimg
        {
 
           top: 0;

            bottom: 0;
            left: 0;
            right: 0;
            margin: 35% 0 0 0%;
            z-index: 9999999999;
        }
    </style>

========================================================================================
 <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="full" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
        <asp:Label ID="lblText" runat="server" />
                <div id="divProgress" style="display:none;" class="popup">
                     <asp:Image ID="LoadingImage" runat="server" ImageUrl="~/images/loader.gif" />                   
                </div>       
        </ContentTemplate>
                <Trigger>
                </Trigger>
    </asp:UpdatePanel>
===========================
 <asp:UpdatePanelAnimationExtender ID="UpdatePanelAnimationExtender1" TargetControlID="full" runat="server">
        <Animations>
            <OnUpdating>                     
               <Parallel duration="0">
                    <ScriptAction Script="InProgress();" />
                    <EnableAction AnimationTarget="Button1" Enabled="false" />     
                    <EnableAction AnimationTarget="LinkButton1" Enabled="false" />        
                    <EnableAction AnimationTarget="LinkButton2" Enabled="false" />              
                </Parallel>
            </OnUpdating>
            <OnUpdated>
                <Parallel duration="0">              
                    <ScriptAction Script="onComplete();" />
                    <EnableAction AnimationTarget="Button1" Enabled="true" />
                    <EnableAction AnimationTarget="LinkButton1" Enabled="true" />        
                    <EnableAction AnimationTarget="LinkButton2" Enabled="true" />   
                </Parallel>
            </OnUpdated>
        </Animations>
        </asp:UpdatePanelAnimationExtender>


split , separated string and bind in gridview in asp.net c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.NetworkInformation;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Runtime.InteropServices;
using System.Management;
using System.Security.Cryptography;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            generatedatatable();
           
        }
    }

    public void generatedatatable()
    {
        try
        {
                  method 1: separate comma and pipe ("," and "|") attached string
            ArrayList List = new ArrayList();             
            //string TstStr = "1,dt3435,26/5/2012 ~ 2,dt738,27/5/2012 ~ 3,dt892,26/5/2012";
            string query = "Select Specification From Menu_new_date where S_no='54'";
            string TstStr = Convert.ToString(connection.scalar(query));
            string[] SplittedString = TstStr.Split('|');
            foreach (string str in SplittedString)
            {
                string ConcatStr = "";
                string[] SubSplit = str.Trim().Split(',');
                foreach (string s in SubSplit)
                {
                    ConcatStr = s " ";
                }
                List.Add(ConcatStr);
            }

            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn("Nutrition", typeof(string));
            //DataColumn dc1 = new DataColumn("Quantity", typeof(string));      
            dt.Columns.Add(dc);
            //dt.Columns.Add(dc1);
            for (int i = 0; i < List.Count; i )
            {
                dt.Rows.Add();
                dt.Rows[i][0] = List[i];
            }
            ------------------------------------------------------------------------------------------

                Method:2  separate comma  (",") attached string in one row with dynamically crate no of column as per the comma
               
            ArrayList List = new ArrayList();
            //string TstStr = "1,dt3435,26/5/2012 ~ 2,dt738,27/5/2012 ~ 3,dt892,26/5/2012";
            string query = "Calories 212 Kcal,Total fat 5.7 g,Saturated fat 0.8 g,Polyunsaturated fats 1 g,Monounsaturated fats 3.4 g,Total                 carbohydrate 25.2 g,Dietary fibre 4.3 g,Sugars 2.3 g,Protein 17.4 g";
            //string TstStr = Convert.ToString(connection.scalar(query));
            string TstStr = query;
            string abc="";
            string[] SplittedString = TstStr.Split(',');
            foreach (string str in SplittedString)
            {
                 abc =str;
                 List.Add(abc);
            }

            DataTable dt = new DataTable();
            //DataColumn dc = new DataColumn("Nutrition", typeof(string));
            //DataColumn dc1 = new DataColumn("Quantity", typeof(string));      
           
            //dt.Columns.Add(dc1);
            dt.Rows.Add();
            for (int i = 0; i < List.Count; i )
            {
                DataColumn dc = new DataColumn("Nutrition" i, typeof(string));
                dt.Columns.Add(dc);
               
               
                dt.Rows[0][i]= List[i];
              
             
            }

            GridView1.DataSource = dt;
            GridView1.DataBind();
            ------------------------------------------------------------------------------------------------

                Method:3  separate comma  (",") attached string in multiple row

            ArrayList List = new ArrayList();
            string TstStr = "1,dt3435,26/5/2012 ~ 2,dt738,27/5/2012 ~ 3,dt892,26/5/2012";
            string query = "Calories 212 Kcal,Total fat 5.7 g,Saturated fat 0.8 g,Polyunsaturated fats 1 g,Monounsaturated fats 3.4 g,Total                 carbohydrate 25.2 g,Dietary fibre 4.3 g,Sugars 2.3 g,Protein 17.4 g";
            string TstStr = Convert.ToString(connection.scalar(query));
            string TstStr = query;
            string abc = "";
            string[] SplittedString = TstStr.Split(',');
            foreach (string str in SplittedString)
            {
                abc = str;
                List.Add(abc);
            }

            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn("Nutrition", typeof(string));
            DataColumn dc1 = new DataColumn("Quantity", typeof(string));      

          
            dt.Columns.Add(dc);
            for (int i = 0; i < List.Count; i )
            {                             
                dt.Rows.Add();
                dt.Rows[i][0] = List[i];
            }
                //create gridview dynamically and add this gridview to any div where to show data
            GridView grid = new GridView();
            grid.DataSource = dt;
            grid.DataBind();
            nutri.Controls.Add(grid);
               
        //bind splitted string to available gridview
            GridView1.DataSource = dt;
            GridView1.DataBind();

                        
Nutrition
Calories 212 Kcal
Total fat 5.7 g
Saturated fat 0.8 g
Polyunsaturated fats 1 g
Monounsaturated fats 3.4 g
Total carbohydrate 25.2 g
Dietary fibre 4.3 g
Sugars 2.3 g
Protein 17.4 g


            --------------------------------------------------------------------------------------------------------
         Method:4  separate  comma and pipe ("," and "|") attached string in multiple row
            DataTable values = new DataTable();
            values.Columns.Add("Nutrition", typeof(string), null);
            values.Columns.Add("Quantity", typeof(string), null);

            string query = "Select Specification From Menu_new_date where S_no='54'";
            string TstStr = Convert.ToString(connection.scalar(query));
            values = TstStr.Split('|').Select(s =>
            {
                var fields = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var row = values.NewRow();
                if (fields.Length == 2)
                {
                    row[0] = fields[0].Trim();
                    row[1] = fields[1].Trim();                  
                }
                return row;
            }).CopyToDataTable();

            GridView1.DataSource = values;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            Label1.Text= ex.Message;
        }
    }
   
}

Automatically update the copyright year in html page in asp.net

Replace Year with below line

<%= DateTime.Now.Year.ToString() %>

How to seach in gridview using key up method like table in html


// Add a gridview to the aspx page and a textbox for search. bind the gridview for populating the data

Put this java script in head of the aspx page

  <script type="text/javascript">
        function filter2(phrase) {
            var words = phrase.value.toLowerCase().split(" ");
            var table = document.getElementById("<%=GridView1.ClientID %>");
            var ele;
            for (var r = 1; r < table.rows.length; r ) {
                ele = table.rows[r].innerHTML.replace(/<[^>] >/g, "");
                var displayStyle = 'none';
                for (var i = 0; i < words.length; i ) {
                    if (ele.toLowerCase().indexOf(words[i]) >= 0)
                        displayStyle = '';
                    else {
                        displayStyle = 'none';
                        break;
                    }
                }
                table.rows[r].style.display = displayStyle;
            }
        }
    </script>

Now add this function "keyup" in the texbox which will be used to enter the keyword like this

 <asp:TextBox ID="TextBox2" runat="server" class="form-control" onkeyup="filter2(this)"></asp:TextBox>

Pagination in Repeater Control in ASP.NET C#

in aspx page drag and drop a repeater control from toolbox

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Perfect Pagination With Repeater and ASP.Net C#</title>
    <link href="admin/css/stylesheet.css" rel="stylesheet" type="text/css" />
   
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="MainScriptManager" runat="server" />
    <asp:UpdatePanel ID="pnlHelloWorld" runat="server">
        <ContentTemplate>
            <div>
                <asp:Repeater ID="rptResult" runat="server">
                    <HeaderTemplate>
                        <table class="mGrid">
                            <tr class="mGrid table_head">
                                <th>
                                    ID
                                </th>
                                <th>
                                    Name
                                </th>
                                <th>
                                    Address
                                </th>
                                <th>
                                    Created Date
                                </th>
                            </tr>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <tr>
                            <td>
                                <%#Eval("PageId") %>
                            </td>
                            <td>
                                <%#Eval("PageName") %>
                            </td>
                            <td>
                                <%#Eval("Section") %>
                            </td>
                            <td>
                                <%#Eval("Department") %>
                            </td>
                        </tr>
                    </ItemTemplate>
                    <FooterTemplate>

                         <tr>
                 <td colspan="4"><asp:Label Visible='<%#bool.Parse((Repeater1.Items.Count==0).ToString())%>' runat="server"    ID="lblNoRecord" Text="No Record Found!" ForeColor="Red"></asp:Label></td>
                </tr>
                        </table>
                    </FooterTemplate>
                </asp:Repeater>
            </div>
            <div style="margin-top: 20px;">
            <asp:Label ID="lblpage" runat="server" Text=""></asp:Label>
                <table>
                    <tr class="mGrid table_head">                      
                        <td>
                            <asp:LinkButton ID="lbFirst" runat="server" OnClick="lbFirst_Click">First</asp:LinkButton>
                        </td>
                        <td>
                            <asp:LinkButton ID="lbPrevious" runat="server" OnClick="lbPrevious_Click">Previous</asp:LinkButton>
                        </td>
                        <td>
                            <asp:DataList ID="rptPaging" runat="server" OnItemCommand="rptPaging_ItemCommand"
                                OnItemDataBound="rptPaging_ItemDataBound" RepeatDirection="Horizontal" RepeatLayout="Table">
                                <ItemTemplate>
                                    <asp:LinkButton ID="lbPaging" runat="server" CommandArgument='<%# Eval("PageIndex") %>'
                                        CommandName="newPage" Text='<%# Eval("PageText") %>'>
                                    </asp:LinkButton>
                                </ItemTemplate>
                            </asp:DataList>
                        </td>
                        <td>
                            <asp:LinkButton ID="lbNext" runat="server" OnClick="lbNext_Click">Next</asp:LinkButton>
                        </td>
                        <td>
                            <asp:LinkButton ID="lbLast" runat="server" OnClick="lbLast_Click">Last</asp:LinkButton>
                        </td>
                       
                    </tr>
                </table>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>


in Code Behind [aspx.cs] page

readonly PagedDataSource _pgsource = new PagedDataSource();
        int _firstIndex, _lastIndex;
        private int _pageSize = 10;
        private int CurrentPage
        {
            get
            {
                if (ViewState["CurrentPage"] == null)
                {
                    return 0;
                }
                return ((int)ViewState["CurrentPage"]);
            }
            set
            {
                ViewState["CurrentPage"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack) return;
            BindDataIntoRepeater();
        }

        // Get data from database/repository
        static DataTable GetDataFromDb()
        {
            string query = "Select * from Page";
            DataTable dt = connection.getDatatbl(query);
            return dt;
        }

        // Bind PagedDataSource into Repeater
        private void BindDataIntoRepeater()
        {
            var dt = GetDataFromDb();
            _pgsource.DataSource = dt.DefaultView;
            _pgsource.AllowPaging = true;
            // Number of items to be displayed in the Repeater
            _pgsource.PageSize = _pageSize;
            _pgsource.CurrentPageIndex = CurrentPage;
            // Keep the Total pages in View State
            ViewState["TotalPages"] = _pgsource.PageCount;
            // Example: "Page 1 of 10"
            lblpage.Text = "Page " (CurrentPage 1) " of " _pgsource.PageCount;
            // Enable First, Last, Previous, Next buttons
            lbPrevious.Enabled = !_pgsource.IsFirstPage;
            lbNext.Enabled = !_pgsource.IsLastPage;
            lbFirst.Enabled = !_pgsource.IsFirstPage;
            lbLast.Enabled = !_pgsource.IsLastPage;

            // Bind data into repeater
            rptResult.DataSource = _pgsource;
            rptResult.DataBind();

            // Call the function to do paging
            HandlePaging();
        }

        private void HandlePaging()
        {
            var dt = new DataTable();
            dt.Columns.Add("PageIndex"); //Start from 0
            dt.Columns.Add("PageText"); //Start from 1

            _firstIndex = CurrentPage - 5;
            if (CurrentPage > 5)
                _lastIndex = CurrentPage 5;
            else
                _lastIndex = 10;

            // Check last page is greater than total page then reduced it
            // to total no. of page is last index
            if (_lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
            {
                _lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
                _firstIndex = _lastIndex - 10;
            }

            if (_firstIndex < 0)
                _firstIndex = 0;

            // Now creating page number based on above first and last page index
            for (var i = _firstIndex; i < _lastIndex; i )
            {
                var dr = dt.NewRow();
                dr[0] = i;
                dr[1] = i 1;
                dt.Rows.Add(dr);
            }

            rptPaging.DataSource = dt;
            rptPaging.DataBind();
        }

        protected void lbFirst_Click(object sender, EventArgs e)
        {
            CurrentPage = 0;
            BindDataIntoRepeater();
        }
        protected void lbLast_Click(object sender, EventArgs e)
        {
            CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
            BindDataIntoRepeater();
        }
        protected void lbPrevious_Click(object sender, EventArgs e)
        {
            CurrentPage -= 1;
            BindDataIntoRepeater();
        }
        protected void lbNext_Click(object sender, EventArgs e)
        {
            CurrentPage = 1;
            BindDataIntoRepeater();
        }

        protected void rptPaging_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (!e.CommandName.Equals("newPage")) return;
            CurrentPage = Convert.ToInt32(e.CommandArgument.ToString());
            BindDataIntoRepeater();
        }

        protected void rptPaging_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            var lnkPage = (LinkButton)e.Item.FindControl("lbPaging");
            if (lnkPage.CommandArgument != CurrentPage.ToString()) return;
            lnkPage.Enabled = false;          
            lnkPage.Attributes.Add("style", "text-align:center;");
        }

Bind dropdown control in asp.net c# from database

protected void bind_servicestype()
    {

        try
        {
            // bind dropdown from database
            string query="select Deposit_Type from Add_Deposit_Type";
            DataSet ds = connection.dataadapter(query);
            DropDownList1.DataSource = ds.Tables[0];
            DropDownList1.DataTextField = "Deposit_Type";
            DropDownList1.DataValueField = "Deposit_Type";
            DropDownList1.DataBind();
          
            // insert a default value in the dropdown
            DropDownList1.Items.Insert(0, new ListItem("---------Select--------", "0"));
        }
        catch (Exception EXP)
        {
            Response.Write(EXP.Message);
        }

Publish or Deploy website in our local machine using asp.net

Here I will explain how to publish or deploy the website in local machine. To publish website first we need to check whether IIS installed in our local machine or not and whether that IIS working properly or not because sometimes IIS will not work properly even that IIS already installed in our local machine for that reason we need to check all these conditions before going to publish or deploy our website in local machine.

After that now open the application in visual studio whatever the application we need publish.

1.  Open the website in that top we have options Build click on that you will find Publish website click on that it will open one wizard in that it will ask target location i.e., the place to save the published application (ex: Create one folder on desktop or any location give that path by using browse button beside of that textbox).

2.   Click on publish it publish all the files into target folder i.e., target location.

3.   Now go to the folder whatever we have given in target location copy that folder and place it in wwwroot folder(path of that folder is C:\Inetpub\wwwroot)

4.   Now open the Run in StartMenu and type inetmgr  and Click Enter it will automatically redirect to IIS

5.   Open the local computer in that open the websites after that open the Default website in that you will find our website because you have already placed our published website in to wwwroot folder. wwwroot folder is the default path for IIS if we place any websites into wwwroot folder it will automatically displays under Default Website

6.   Click on the your website right side it will display all of your published pages select whatever the page first you need to run right click on that and click browse it will display your published website.

7.   At that time if you get any error please right click on website in Default Website goes to Properties and click on Create button and click Ok button. Now browse your default page.

This is the one way to publish the website
=============================================================================================
Another way is

1.   Type inetmgr in run command it will open IIS

2.   Click on local computer in that open the websites after that open the Default website and right click on Default website in that click New option in that select Virtual Directory click on that one wizard will open click on NEXT after that it will ask Alias name give some name to display in Default website click Next now it will ask path for website give the path of your website whatever the application you to want publish or deploy after that click Next in that select Read, Run Scripts click next click finish button.

3.   Now your website has been published open that website in Default website select the Default page right click on that select browse option now your website will display.

4.   At that time if you get any error please right click on website in Default Website goes to Properties and click on Create button and click Ok button. Now browse your default page.

5.   Then make the website as application by right click on the website.

6.   Right click on the application pool of the inetmgr(IIS manager) and right click on DefaultAppPoolgo in App Pool Part. Choose  Advance Setting and  go to Process Model Category and select
Identitty. click on browse button and select Built-In Account and set the dropdown value as NetworkService.

Create a user in the database as NT AUTHORITY\NETWORK SERVICE with same login name. it will make the website accessible through out the lan by typin the ip address of the hosted
machine on netwok computer.
==============================================================================================================================================

ADO DOT NET, Connection, Command and DataReader object




ADO DOT NET (Active Data Object)

[DEFINATION] It’s a component in dot net framework which helps us to fetch data from different data source to c# or from C# code to data sources.

ADO DOT NET comprises of 6 components:


1.      Connection- Compulsory
2.      Command - Compulsory
3.      Data Reader
4.      Data Adapter
5.      Data Set
6.      Data View



In these 6 components 2 components are compulsory (connection and command)


Connection Object - this object is needed to connect to data source like Sql-Server, Oracle, MySql etc to use this object at least two things are required.
a.       Data source- where database is located either in local host or on remote host.
b.      Security credentials -like windows authentication, user id and password.

    Command Object- Sql syntaxes are written here and it helps to execute the Sql query. 

    Data Reader -  [Connected, Read Only and Forward Only Record Set]
Data Adapter - It’s bridge between data source and dataset. It actually fills the dataset with data coming from database. 

Data Set It’s a disconnected record set which can be browsed forth and back direction and can also be updated.

Difference B/W DataReader and DataSet
#
DataReader                                                 DataSet

1.
Its collection of connected records                  Its collection of disconnected records.

2.
It can only be accessed in forward mode         It can be accessed in forward and backward mode.

3.
Records in DataReader cannot be updated      Records in DataSet can be updated.