Pages

Monday, 24 February 2014

Update and Delete Top N records

Once table created enter some dummy data like as shown below

Check below methods to use Top keyword or clause with update and delete statements

Top keyword with Update Statement

Syntax to use top keyword with update statement

UPDATE TOP(N) Table1 SET Column1='somevalue'
Example

UPDATE TOP(2) UserInformation SET UserName='test2'
Once we run above query our table UserInformation will contain data like as shown below

Output

Top keyword with delete statement

Syntax to use top keyword with delete statement

DELETE TOP(N) FROM Table1
Example

DELETE TOP(2) FROm UserInformation
Once we run above query our table UserInformation will contain data like as shown below

Page life cycle in asp.net

When a page request is sent to the Web server, the page is run through a series of events during its creation and disposal. In this article, I will discuss in detail the ASP.NET page life cycle Events
 (1) PreInit The entry point of the page life cycle is the pre-initialization phase called “PreInit”. This is the only event where programmatic access to master pages and themes is allowed. You can dynamically set the values of master pages and themes in this event. You can also dynamically create controls in this event. 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

using System;

using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page{    protected void Page_PreInit(object sender, EventArgs e)    {        //  Use this event for the following:          //  Check the IsPostBack property to determine whether this is the first time the page is being processed.        //  Create or re-create dynamic controls.       //  Set a master page dynamically.        //  Set the Theme property dynamically.           }

------------------------------------------------------------------------

(2)Init This event fires after each control has been initialized, each control's UniqueID is set and any skin settings have been applied. You can use this event to change initialization values for controls. The “Init” event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself.  

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_Init(object sender, EventArgs e)

{// Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.}

 -------------------------------------------------------------------

(3)InitComplete Raised once all initializations of the page and its controls have been completed. Till now the viewstate values are not yet loaded, hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_InitComplete(object sender, EventArgs e)

{       // Raised by the  Page object. Use this event for processing tasks that require all initialization be complete. }

------------------------------------------------------------------------

(4)PreLoad Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance     

(1)Loads ViewState : ViewState data are loaded to controls

Note : The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden <input> control that is passed from page request to page request.     

(2)Loads Postback data : postback data are now handed to the page controls            

Note : During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. Hence, the page fires the LoadPostData event and parses through the page to find each control and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control's unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page. 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected override void OnPreLoad(EventArgs e)

{        // Use this event if you need to perform processing on your page or control before the  Load event.        // Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.}

------------------------------------------------------------------------

(5)Load The important thing to note about this event is the fact that by now, the page has been restored to its previous state in case of postbacks. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. This method is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method.

 EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_Load(object sender, EventArgs e)

{        // The  Page calls the  OnLoad event method on the  Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded.        // Use the OnLoad event method to set properties in controls and establish database connections.}

------------------------------------------------------------------------

(6)Control (PostBack) event(s)ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event or a dropdown's selectedindexchange event, for example.These are the events, the code for which is written in your code-behind class(.cs file). 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Button1_Click(object sender, EventArgs e)

{        // This is just an example of control event.. Here it is button click event that caused the postback}

---------------------------------------------------------------------

(7)LoadComplete This event signals the end of Load. 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_LoadComplete(object sender, EventArgs e)

{        // Use this event for tasks that require that all other controls on the page be loaded.}

----------------------------------------------------------------------

(8)PreRender Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called. 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected override void OnPreRender(EventArgs e)

{        // Each data bound control whose DataSourceID property is set calls its DataBind method.        // The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.}

-----------------------------------------------------------------------

(9)SaveStateComplete Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected override void OnSaveStateComplete(EventArgs e)

{        // Before this event occurs,  ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.        // Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.}

------------------------------------------------------------------------

(10)Render This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.

 Note: Right click on the web page displayed at client's browser and view the Page's Source. You will not find any aspx server control in the code. Because all aspx controls are converted to their respective HTML representation. Browser is capable of displaying HTML and client side scripts. 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

// Render stage goes here. This is not an event

------------------------------------------------------------------------

(11)UnLoad This event is used for cleanup code. After the page's HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. Cleanup can be performed on- 

     (a)Instances of classes i.e. objects

     (b)Closing opened files

     (c)Closing database connections. 

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_UnLoad(object sender, EventArgs e)   

{        // This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.        // During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream.           //If you attempt to call a method such as the Response.Write method, the page will throw an exception.    }

-----------------------------------------------------------------

JQuery script src common links

Common:

<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

BEST faster than all
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> 

http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js
http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

Simple login page button in asp.net

 protected void Button1_Click(object sender, EventArgs e)
    {
        Session["name"] = Convert.ToString(TextBox1.Text);
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con1"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("loginselection", con);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@username", TextBox1.Text);
        cmd.Parameters.AddWithValue("@password", TextBox2.Text);
        int a=Convert.ToInt32(cmd.ExecuteScalar());
        if (a > 0)
        {
            Label1.Text = "login sucessfully";
            Response.Redirect("~/Coursetopics.aspx");
            
        }
        else
        {
            Label1.Text = "check your username and password";
        }
            
       
    }





ALTER PROCEDURE [dbo].[loginselection](
@username varchar(20) ,
@password  varchar(20)

)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

    -- Insert statements for procedure here
SELECT * from UserDetails where UserName= @username and PsWrd =@password 
END

Calendar control in asp.net

 protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {
        //if (e.Day.IsWeekend)
        //{
        //    e.Cell.BackColor = Color.Black;
        //}
        // if (e.Day.DayNumberText == "25" && e.Day.Date.Month.ToString().ToLower().Trim() == "January")
        if (e.Day.Date == new DateTime(2013,1,27))
        {
            e.Cell.BackColor = System.Drawing.Color.Red;
            e.Cell.ForeColor = Color.Red;
        }

        if (e.Day.Date.ToLongDateString().Contains("29"))
        {
            e.Cell.ForeColor = Color.Red;
        }

    }

AdRotator control in asp.net

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Rotatorcontrol.aspx.cs" Inherits="Rotatorcontrol" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    
   <div>
   <asp:ScriptManager ID="ScriptManager1" 
                      runat="server">
   </asp:ScriptManager>
    
   <asp:Timer ID="Timer1" runat="server" 
              Interval="1500">
   </asp:Timer>
    
   <asp:UpdatePanel ID="UpdatePanel1" 
                    runat="server">
   <Triggers>
   <asp:AsyncPostBackTrigger ControlID="Timer1" 
                             EventName="Tick" />
   </Triggers>
    
   <ContentTemplate>
   <asp:AdRotator ID="AdRotator1" runat="server" 
                  AdvertisementFile="~/RotatorXML.xml"
                  KeywordFilter="Asp.Net">
   </asp:AdRotator>
   </ContentTemplate>
   </asp:UpdatePanel>
   </div>
  
    </form>
</body>
</html>



XML File:::

<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
  <Ad>
    <ImageUrl>~/images (1).jpg</ImageUrl>
    <NavigateUrl>http://www.google.com</NavigateUrl>
    <AlternateText>AdRotator Control sample ads</AlternateText>
    <Impressions>20</Impressions>
    <Keyword>Asp.Net</Keyword>

  </Ad>
  <Ad>
    <ImageUrl>~/images.jpg</ImageUrl>
    <NavigateUrl>http://csharpdotnetfreak.blogspot.com</NavigateUrl>
    <AlternateText>AdRotator Control sample ads  </AlternateText>
    <Impressions>30</Impressions>
    <Keyword>Asp.Net</Keyword>

  </Ad>

</Advertisements>

Images Slideshow in jQuery

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Slideshow.aspx.cs" Inherits="Slideshow" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            LoadXmlToArray();

        });

        var LoadXmlToArray = function () {
            var imgpath = new Array();
            var tem = 0;
            $.ajax({
                type: "GET",
                url: "XML1.xml",
                cache: false,
                dataType: "xml",
                async: false,
                success: function (xml) {

                    $(xml).find('Table', xml).each(function () {

                        tem++;
                        var $Table = $(this);

                        imgpath[tem] = $Table.find('imgpath').text();

                    });
                    var htmltag = "";
                    var flag = 0;
                    //                    flag++;
                    //                    htmltag = '<img class="fadeimg" src="' + imgpath[flag] + '" style="width:521px; opacity:1.0; height:359px" /></li>';
                    //                   
                    //                    $(".slide").html(htmltag);
                    //                    $(".slide").hover(function () {
                    //                        flag++;

                    //                        htmltag = '<img class="fadeimg" src="' + imgpath[flag] + '" style="width:521px; opacity:1.0; height:359px" /></li>';

                    //                        $(".slide").html(htmltag);
                    //                        $(".fadeimg").animate({ opacity: '1.0' }, 3000);

                    //                        $(".fadeimg").fadeOut(3000);

                    //                        if (flag >= imgpath.length - 1) {
                    //                            flag = 1;
                    //                        }
                    //                    });

                    var slide = setInterval(function () {
                        flag++;

                        htmltag = '<img class="fadeimg" src="' + imgpath[flag] + '" style="width:400px; opacity:0.1; height:300px" /></li>';

                        $(".slide").html(htmltag);
                        $(".fadeimg").animate({ opacity: '1.0' }, 2000);

                        $(".fadeimg").fadeOut(2000);
                        $(".fadeimg").hover(function () {
                            $(".fadeimg").css({ "width": "600px", "height": "550px" });

                        });

                        if (flag >= imgpath.length - 1) {
                            flag = 1;
                        }
                    }, 4000);

                }
            });

        }
        

       
    

        

    </script>
    <style type="text/css">
        .style1
        {
            font-family: Arial;
        }
        
        .fadeimg:hover
        {
            width: 500px;
            height: 500px;
        }
    </style>
</head>
<body style="background-color: Green; font-family: Aharoni;">
    <form id="form1" runat="server">
    <div style="position: absolute; top: 31px; left: 383px; font-size: 50px; color: #FF0000;
        width: 277px; height: 59px;">
        <span class="style1"><strong><em>Slide Show</em></strong></span>
    </div>
    <div>
        <div class="slide" style="position: absolute; top: 102px; left: 279px; height: 359px;
            width: 521px;">
            <%-- background-image : url('images/images.jpg')">--%>
        </div>
    </div>
    </form>
</body>
</html>

Timer in JQuery

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DragAndDropGame.aspx.cs"
    Inherits="DragAndDropGame" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>jQuery UI Sortable - Display as grid</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css" />
    <style type="text/css">
        #sortable
        {
            background-color: red;
            list-style-type: none;
            margin: 0;
            padding: 0;
            width: 422px;
            position: absolute;
            top: 48px;
            left: 59px;
            height: 295px;
            border-radius: 15px;
        }
        #sortable li
        {
            margin: 3px 3px 3px 0;
            padding: 1px;
            float: left;
            width: 100px;
            height: 90px;
            font-size: 4em;
            text-align: center;
            background-color: Olive;
            border-radius: 15px;
        }
        #sortable:hover
        {
            background-color: Green;
        }
        #maindiv
        {
            position: absolute;
            top: 196px;
            left: 351px;
            width: 539px;
            height: 403px;
        }
        .style3
        {
            font-size: large;
        }
        .style4
        {
            color: #FF0066;
            font-size: large;
        }
        .style5
        {
            font-family: Arial, Helvetica, sans-serif;
        }
        .style6
        {
            text-decoration: underline;
        }
        .style7
        {
            color: #FF0000;
        }
        .style8
        {
            font-family: "Arial Black";
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function () {
            timer1.innerHTML = 60;
            $("#btn1").click(function () {

                alert("Game Starts Now...!");

                var count = timer1.innerHTML.toString();
                debugger;
                function timer() {

                    count--;
                    timer1.innerHTML = count.toString();
                    setTimeout(function () { timer() }, 1000);
                }
                $(function () {
                    timer();
                    $("#sortable").sortable();
                    $("#sortable").disableSelection();
                });

                var item = new Array();
                setInterval(function () {

                    var check = $(function () {
                        var flag = 0;
                        var test = 12;
                        var result = 0;
                        $('.c2').each(function () {
                            $(this).find("li").each(function () {
                                flag++;

                                item[flag] = $(this).text();
                                if (item[flag] == test) {
                                    result++;
                                }
                                else {
                                    result = 0;
                                }
                                test--;

                            });
                            if (result > 11) {
                                alert("you win the game");
                                window.location.reload();
                            }
                            else {
                                alert("you loose the game\n Please Try Again.");
                                window.location.reload();
                                
                            }

                        });
                    });

                }, 60000);
            });
        });
    </script>
</head>
<body>
    <div>
        <img src="http://wallpoper.com/images/00/42/25/63/numbers_00422563.jpg" style="height: 674px;
            width: 1350px;" />
        <div class="c1" id="maindiv"><span></span>
            <span id="timer1" style="position: absolute; top: 12px; left: 236px; width: 54px;
                font-size: x-large; color: #FF0000; text-decoration: underline;
                background-color: #FFCCFF; border-radius:15px; text-align: center;"></span> 
            <span id="Span1" style="position: absolute; top: 11px; left: 283px; width: 172px;
                height: 28px; font-size: x-large; color: #FF0000; text-decoration: underline;
                background-color: #FFCCFF; border-radius:15px; text-align: center;">Secs Remaining.</span>
            <ul class="c2" id="sortable">
                <li class="style8"><strong style="color: #FF0000">1</strong></li>
                <li><strong style="font-family: 'Arial Black'">2</strong></li>
                <li><strong style="font-family: 'Arial Black'">3</strong></li>
                <li class="style8"><strong>4</strong></li>
                <li><strong style="font-family: 'Arial Black'">5</strong></li>
                <li><strong style="font-family: 'Arial Black'">6</strong></li>
                <li><strong style="font-family: 'Arial Black'">7</strong></li>
                <li><strong style="font-family: 'Arial Black'">8</strong></li>
                <li><strong style="font-family: 'Arial Black'">9</strong></li>
                <li><strong style="font-family: 'Arial Black'">10</strong></li>
                <li><strong style="font-family: 'Arial Black'">11</strong></li>
                <li class="style7"><strong style="font-family: 'Arial Black'">12</strong></li>
            </ul>
        </div>
        <div style="position: absolute; top: 36px; left: 26px; height: 98px; width: 194px;">
            <strong><span class="style3">
                <br />
            </span></strong><span class="style4"><strong><em><span class="style5">Arrange the numbers
                in reverse order with </span>
                <br class="style5" />
            </em></strong><span style="color: #FF0000" class="style5"><strong><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <span class="style6">1 Minute.</span></em></strong></span></span>
        </div>
        <input type="button" id="btn1" style="position: absolute; border-radius: 15px; top: 50px;
            left: 242px; font-weight: 700; font-size: x-large; text-decoration: underline;
            color: #FF0000; background-color: #002661; width: 275px; height: 50px; right: 436px;"
            value="Click to Start the Game" />
    </div>
</body>
</html>

Face book likes box in jQuery

 <div style="position:absolute;  top: 189px; left: 729px;  background-color: #9999FF" 
            id="fb-root">
        </div>
        <div style="position:absolute; top: 138px;  left: 729px; background-color: #9999FF" 
            class="fb-like-box" 
            data-href="https://www.facebook.com/InnuGame?ref=br_tf" data-width="202"
            data-show-faces="true" data-stream="true" data-show-border="true" 
            data-header="true">
        </div>


<script type="text/javascript">
        (function (d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s); js.id = id;
            js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
            fjs.parentNode.insertBefore(js, fjs);
        } (document, 'script', 'facebook-jssdk'));
</script>

JQuery radio button validation

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {

            $("#btn").hide();

            $("input[type=radio]").click(function () {

                check();
            });
        });
        var check = function () {

            if (($('input[name=color]').is(":checked")) && ($('input[name=size]').is(":checked"))) {

                $("#btn").show();

            }
            else {

                $("#btn").hide();

       
            }
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="radio" name="color" value="red" />red
        <br />
        <input type="radio" name="color" value="green" />green<br />
        <input type="radio" name="size" value="red" />36
        <br />
        <input type="radio" name="size" value="green" />38
    </div>
    <input type="button" id="btn" value="hi welcome" />
    </form>
</body>
</html>

JQuery check box validation

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApplication4.WebForm3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btn").hide();
            $('input[type=checkbox]').click(function () {
                if ($('input[type=checkbox]').is(":checked")) {
                    
                    $("#btn").show();
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="checkbox" value="blue" name="color" />blue
        <br />
        <input type="checkbox" value="green" name="color" />green
        <br />
        <input type="checkbox" value="red" name="color" />red
        <br />
        <input type="button" id="btn" value="show" />
    </div>
    </form>
</body>
</html>

Jquery Date validation

 function DateDifference(obj) {
            var DateValue = $(obj).text();
            var EDDDate = new Date(DateValue);
            var CurrentDate = new Date(document.getElementById("hdnCurDate").value);
            var DiffDate = ((((CurrentDate - EDDDate) / 1000) / 60) / 60) / 24;
            if (DiffDate >= 1) {
                $(obj).css("color", "Red");
            }
            else if (DiffDate > -3 && DiffDate < 1) {
                $(obj).css("color", "Blue");
            }
            else if (DiffDate <= -3) {
                $(obj).css("color", "Black");
            }
        }




var date1 = Date.parse("24-Feb-2014");
                var date = Date.parse("25-Feb-2014");
                if (date1 > date) {
                    alert("hi");
                } else {
                alert("poi");
                }





var date = new Date("24-Feb-2014");
                var sysdate = new Date("yourdate");
                var month = date.getMonth();
                var sysmonth = sysdate.getMonth();

                var day = date.getDate();
                var sysday = sysdate.getDate();

                var year = date.getYear();
                var sysyear = sysdate.getYear();
                if (month > sysmonth && date > sysdate && year > sysyear) {
                    alert("Greater");
                }

Friday, 21 February 2014

Serialization in .net

Serialization:
                                                           
XML Serialization:

Object Serialization is a process through which an object's state is transformed into some serial data format, such as XML or binary format, in order to be stored for some later use. In other words, the object is "dehydrated" and put away until we need to use it again.

Some good uses for serialization/deserialization include: 
Storing user preferences in an object.
Maintaining security information across pages and applications.
Modification of XML documents without using the DOM.
Passing an object from on application to another.
Passing an object from one domain to another.
Passing an object through a firewall as an XML string. 
XML Serialization: It is limited that it can serialize only public members.
Required Namespace :
         
using System.Xml;
using System.Xml.Serialization;
 
Create XSD file from Class: 

Object instance into XML file
 
Create one web project and add Person.cs class file.

using System;
using System.Xml;
using System.Xml.Serialization;
 
namespace XMLSerialization
{
    /// <summary>
    /// Summary description for Person.
    /// </summary>
    [XmlRoot("Class_Person")]
    public class Person
    {
        private string m_sName;
        private int m_iAge;
        public Person()
        {}
        [XmlElement("Property_Name")]
        public string Name
        {
            get     {return m_sName;}
            set {m_sName=value;}
        }
        [XmlElement("Property_Age")]
        public int Age
        {
            get{return m_iAge;}
            set{m_iAge=value;}
        }
        public string Hello()
        {
            return "Hi! My name is " + Name + " and I am " + Age.ToString() + " years old";
        }
        public string GoodBye()
        {
            return "So long";
        }
    }
}

[XMLRoot()] and [XMLElement()] these are the .net attributes and tell the serializer where the various members of this object will appear in the XML document and what they will be named. Without these, serialization cannot take place.
 
XmlSerializer objXmlSer = new XmlSerializer(typeof(Person));
Person objLucky = new Person();                      
StreamWriter objStrWrt;                        
objLucky.Name = "Myname";
objLucky.Age = 30;
 
Response.Write(objLucky.Hello());
Response.Write(objLucky.GoodBye());
objStrWrt = new StreamWriter(Server.MapPath("abc.xml"));
objXmlSer.Serialize(objStrWrt,objLucky);
objStrWrt.Close();
 
First of al, we declare and instantiate an XMLSerializer object. The typeof() function describes what type of object it's going to be serializing. Then we assign Name and Age properties of the Person object. Then we used to see the output of that object by calling Hello() and GoodBye() functions. Then we initiates a StreamWriter object and that it will be writing to a file call abc.xml. We then call the Serialize() method of the XMLSerializer object and send it our person object to be serialized as well as the StreamWriter object so it will write the resulting XML to the file specified. Then we close the StreamWriter.
 
The Abc.Xml file is look like.

<Xml version="1.0" encoding="utf-8" ?>
<c- <Class_Person xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Property_Name>TestProperty1 </Property_Name>
  <Property_Age>30</Property_Age>
  </Class_Person>
 
Create class object from XML file: 

XML file into Object instance.

Now, make some changes in your abc.xml file.
<xml version="1.0" encoding="utf-8" ?> 
<Class_Person xmlns:xsd= "http://www.w3.org/2001/XMLSchema" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance">
 <Property_Name>TestProperty2</Property_Name> 
  <Property_Age>32</Property_Age> 
  </Class_Person>

First create instance of Person class. Next, we create an instance of StreamReader object and feed it the stored XML file. Then we instantiate the Person object by calling the deserialize() method of the XMLSerializer object. This method use the StreamReader object to read the content of the XML file. You have to explicitly casting the type to Person type.

Person objDesPerson = new Person();
StreamReader objStrRdr;
objStrRdr = new StreamReader(Server.MapPath("abc.xml"));
XmlSerializer objXmlSer = new XmlSerializer(typeof(Person));
objDesPerson = (Person)objXmlSer.Deserialize(objStrRdr);
Response.Write(objDesPerson.Name);
Response.Write(objDesPerson.Age.ToString());
objStrRdr.Close(); 
 
Binary Serialization :
 
public class Article
{
    public string sTitle;
    public string sAuthor;
    public string sText;
}
 
Not much to this class, just a few string variables. Lets suppose that we need to write an instance of this call tout to disk. To do this, we can use binary serialization. This will create a binary file that can be read back in as an instance of Article. To do this, we will need to implement 2 methods GetObjectData and Overloaded Constructor.
 
It will requires following namespace:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
 
First we will make the class with serializable attribute and implements the ISerializable interface.
 
[Serializable()]
public class Articles :ISerializable
 
We have to implements GetObjectData method of ISerializable interface.
 
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
    info.AddValue("Title", sTitle);
    info.AddValue("Author", sAuthor);
    info.AddValue("Text", sText);
}

This method will allow you to serialize the objects to disk. We could add any code in here that we wanted to customize the way the data is serialized.

Now we need a method to retrieve the data from a serialized object then we will use a overloaded constructor for this.
 
public Articles(SerializationInfo info,StreamingContext context)
{
    sTitle =Convert.ToString(info.GetValue("Title",typeof(String)));
    sAuthor = Convert.ToString(info.GetValue("Author",typeof(String)));
    sText = Convert.ToString(info.GetValue("Text",typeof(String)));
}
 
The empty constructor is added here so that you can create a new Article object without deserialized one.
 
Now we have a class that can be serialized and deserialized. For serializing this class we have to create methods like
 
Serializing the object 

public void serialize(string fileName)
{
    FileStream s = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
    BinaryFormatter B = new BinaryFormatter();
    B.Serialize(s, this);
    s.Close();
}
 
Here first we create an instance of FileStream class which, will create file and open it in read and write mode. Next we create an instance of BinaryForamtter class. This class have Seralize method which take parameters FileStream and Instance which you want to serialize.
 
DeSerializing the object 

public Articles deSerialize(string fileName)
{
    FileStream Fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    BinaryFormatter F = new BinaryFormatter();
    Articles s1 = (Articles)F.Deserialize(Fs);
    Fs.Close();
    return s1;
} 

Here again create an instance of BinaryFormatter. The method Deserialize() will take parameter of FileStream object which point to the binary file which you want to deserialize. You have to do explicit casting of Article type during Deserializing.
 
Create One Project For Serializing:
 
Create one Articles.cs class file
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace BinarySerialization
{
    [Serializable()]
    public class Articles :ISerializable
    {
        public string sTitle;
        public string sAuthor;
        public string sText;
 
        public Articles()
        {}
        public Articles(SerializationInfo info,StreamingContext context)
        {
            sTitle =Convert.ToString(info.GetValue("Title",typeof(String)));
            sAuthor = Convert.ToString(info.GetValue("Author",typeof(String)));
            sText = Convert.ToString(info.GetValue("Text",typeof(String)));                   
        }
        public void serialize(string fileName)
        {
            FileStream s;
            s = new FileStream(fileName,FileMode.Create,FileAccess.ReadWrite);
            BinaryFormatter B = new BinaryFormatter();
            B.Serialize(s,this);
            s.Close();
        }
        public Articles deSerialize(string fileName)
        {
            FileStream Fs = new FileStream(fileName,FileMode.Open,FileAccess.Read);
            BinaryFormatter F = new BinaryFormatter();
            Articles s1 = (Articles)F.Deserialize(Fs);                       
            Fs.Close();
            return  s1;
        }
        #region ISerializable Members
 
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Title",sTitle);
            info.AddValue("Author",sAuthor);
            info.AddValue("Text",sText);
        }
        #endregion
    }
} 
 
Create one webForm1.aspx page for testing the binary serialization.
 
//Binary Serialization of the object
Articles c1 = new Articles();
c1.sTitle = "My Title";
c1.sAuthor = "Author Name";
c1.sText ="This is my Text";
c1.serialize(@"C:\123.txt");
   
//deserialization of the object
Articles c2 = c1.deSerialize(@"C:\123.txt");
Response.Write(c2.sTitle);
Response.Write(c2.sAuthor);
Response.Write(c2.sText);

Gridview events

Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView in asp.net C#

Click on Image to enlarge
Introduction: In this article I am going to explain How to perform Bind, Insert/Save, Edit, Update, Cancel, Delete, Paging in GridView in asp.net using C# language.
Basically you will learn the following through this example: 
How to Save/Insert and update data in Sql Server Database from asp.net web application?
How to Bind Data from Sql Server to GridView Data Control?
How to perform Edit, Update and Delete operation in GridView?
How to Fill Day, Month and Year in DropDownList and set current date as selected?
How to find controls like TextBox and DropDownList placed inside GridView and get their values?
How to implement paging in GridView?

In previous articles i explained How to Bind,Insert,Edit,Update,Delete in GridView in asp.net VB.Net and WCF Service to bind,insert,edit,update,delete from sql server database in asp.net C# and Bind,upload,download,delete image files from the GridView in asp.net using Sql Server as a back end database and  How to upload, download and delete files from GridView in Asp.net? and  How to bind gridview using SqlDataAdapter,DataSet and Stored procedure in Asp.net  and Bind and Export GridView data to PDF file in asp.net(C#, VB.Net)  and How to bind empty GridView with header and custom message when no data present in Datatable and some other GridView Examples .

Click on image  to enlarge
First of all create the Database in Sql Server and Name it "Emp_DB" or whatever you want. Create a Table having columns as shown in figure and  name it "Emp_Tb" .
Note: Emp_Id_Pk column is set to Primary key and Identity specification is set to yes with Identity increment and Identity seed equal to 1.
In the Web.config file create the connection string as:
<connectionStrings>
                                <add name="conStr"connectionString="Data Source=LocalServer;Initial Catalog=Emp_DB;Integrated Security=True"/>
                </connectionStrings>

Create a folder in the root directory and name it "Images". Search edit and delete .png icon image from the google search and add in the "Images" folder.
  Now In the Design page(.aspx) design  the  web page as:
Note: I have also implemented the asp.net validations on the Employee Name, Address and the Salary fields.

<fieldset style="width:545px;">
    <legend style="font-size:20px; color:Green;">Save, Edit, Update, Delete, Paging example in
        Gridview</legend>   
        <table>
            <tr>
                <td>
                    Employee Name</td>
                <td>
                    <asp:TextBox ID="txtEmployeeName" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvEmpName" runat="server"
                        ErrorMessage="Please enter employee name"
                        ControlToValidate="txtEmployeeName" Display="Dynamic" ForeColor="Red"
                        SetFocusOnError="True"></asp:RequiredFieldValidator>
                </td>
            </tr>           
            <tr>
                <td>
                    Address</td>
                <td>
                    <asp:TextBox ID="txtAddress" runat="server" TextMode="MultiLine"Height="59px"
                        Width="267px"></asp:TextBox><asp:RequiredFieldValidator ID="rfvAddress"runat="server"
                        ErrorMessage="Please enter Address"
                        ControlToValidate="txtAddress" Display="Dynamic" ForeColor="Red"
                        SetFocusOnError="True"></asp:RequiredFieldValidator>
                </td>
            </tr>           
            <tr>
                <td>
                    DOJ</td>
                <td>
                    <asp:DropDownList ID="ddlYear" runat="server"  ToolTip="Select Year"
                        onselectedindexchanged="ddlYear_SelectedIndexChanged">
                    </asp:DropDownList>
                    <asp:DropDownList ID="ddlMonth" runat="server" ToolTip="Select Month"
                        onselectedindexchanged="ddlMonth_SelectedIndexChanged">
                    </asp:DropDownList>
                    <asp:DropDownList ID="ddlDay" runat="server" ToolTip="Select Day">
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>
                    Salary</td>
                <td>
                    <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvSal" runat="server"
                        ErrorMessage="Please enter salary" ControlToValidate="txtSalary"
                        Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
                </td>
            </tr>      
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
                    <asp:Button ID="btnReset" runat="server" Text="Reset" CausesValidation="false"
                        onclick="btnReset_Click" />
                </td>
            </tr>           
            </table>   

        <asp:GridView ID="grdEmp" runat="server"
            DataKeyNames="Emp_Id_Pk"  CssClass="rowHover" RowStyle-CssClass="rowHover"
            AutoGenerateColumns="False" AllowPaging="True"onpageindexchanging="grdEmp_PageIndexChanging"
            PageSize="4" onrowcancelingedit="grdEmp_RowCancelingEdit"
            onrowdeleting="grdEmp_RowDeleting" onrowediting="grdEmp_RowEditing"
            onrowupdating="grdEmp_RowUpdating"onrowdatabound="grdEmp_RowDataBound"
             CellPadding="4" ForeColor="#333333" GridLines="None">          
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />          
         <Columns>          
                <asp:TemplateField HeaderText="Emp Name" HeaderStyle-HorizontalAlign="Center">
            <ItemTemplate>
                 <%#Eval("EmpName")%>
            </ItemTemplate>
            <EditItemTemplate>
                 <asp:TextBox ID="txtEmpName" runat="server" Text='<%#Eval("EmpName") %>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvEmpName" runat="server" ErrorMessage="*"ForeColor="red" ControlToValidate="txtEmpName" Display="Dynamic"SetFocusOnError="True"></asp:RequiredFieldValidator>
             </EditItemTemplate>
              <HeaderStyle HorizontalAlign="Center" />            
         </asp:TemplateField>       
        <asp:TemplateField HeaderText="Address" HeaderStyle-HorizontalAlign="Center">
            <ItemTemplate>
                 <%#Eval("Address")%>
            </ItemTemplate>
            <EditItemTemplate>
                 <asp:TextBox ID="txtEditAddress" runat="server" Text='<%#Eval("Address") %>' TextMode="MultiLine"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvAddress" runat="server" ErrorMessage="*"ForeColor="red" ControlToValidate="txtEditAddress" Display="Dynamic"SetFocusOnError="True"></asp:RequiredFieldValidator>
             </EditItemTemplate>
              <HeaderStyle HorizontalAlign="Center" />            
         </asp:TemplateField>
        <asp:TemplateField HeaderText="DOJ" HeaderStyle-HorizontalAlign="Center"ItemStyle-Width="180px">
         <ItemTemplate>
        <%#Eval("DOJ", "{0:dd/MM/yyyy}")%>   
         </ItemTemplate>
         <EditItemTemplate>
               <asp:DropDownList ID="ddlEditDay" runat="server" ToolTip="Select Day">
              </asp:DropDownList>
              <asp:DropDownList ID="ddlEditMonth" runat="server" ToolTip="Select Month">
                    </asp:DropDownList>
              <asp:DropDownList ID="ddlEditYear" runat="server" ToolTip="Select Year">
                    </asp:DropDownList>
         </EditItemTemplate>        
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Center" Width="180px" />        
         </asp:TemplateField>
           <asp:TemplateField HeaderText="Salary" HeaderStyle-HorizontalAlign="Center">
            <ItemTemplate>
                 <%#Eval("Salary")%>
            </ItemTemplate>
            <EditItemTemplate>
                 <asp:TextBox ID="txtSal" runat="server" Text='<%#Eval("Salary") %>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvSal" runat="server" ErrorMessage="*"ForeColor="red" ControlToValidate="txtSal" Display="Dynamic" SetFocusOnError="True"></asp:RequiredFieldValidator>
             </EditItemTemplate>
              <HeaderStyle HorizontalAlign="Center" />             
         </asp:TemplateField>
                   <asp:TemplateField HeaderText="Edit"  HeaderStyle-HorizontalAlign="Center"ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>             
                <asp:ImageButton ID="imgEdit" runat="server" CommandName="Edit" ImageUrl="~/Images/Edit.png" ToolTip="Edit" CausesValidation="false"/>
            </ItemTemplate>
            <EditItemTemplate>
                 <asp:LinkButton ID="lkUpdate" runat="server" Text="Update"CommandName="Update" ToolTip="Update" CausesValidation="false"></asp:LinkButton>
                 <asp:LinkButton ID="lkCancel" runat="server"  Text="Cancel"CommandName="Cancel" ToolTip="Cancel" CausesValidation="false"></asp:LinkButton>               
             </EditItemTemplate>
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Center" />
         </asp:TemplateField>
         <asp:TemplateField HeaderText="Delete"  HeaderStyle-HorizontalAlign="Center"ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                 <asp:ImageButton ID="imgDelete" runat="server" CommandName="Delete" ImageUrl="~/Images/Delete.png" OnClientClick="return confirm('Are you sure you want to delete selected record ?')" ToolTip="Delete" CausesValidation="false"/>
            </ItemTemplate>           
             <HeaderStyle HorizontalAlign="Center" />
             <ItemStyle HorizontalAlign="Center" />
         </asp:TemplateField>   
                  </Columns>        
             <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle CssClass="rowHover" BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"/>
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />       
         </asp:GridView>    
         </fieldset>

C#.Net Code to Bind, Save, Edit, Update, Cancel, Delete, Paging example  in GridView
In the Code behind file (.aspx.cs) write the code as:
#region "namespaces"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
#endregion

public partial class _Default : System.Web.UI.Page
{ 
    //Creating Connection object and getting connection string
    SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

    #region "page Load"
    protected void Page_Load(object sender, EventArgs e)
    {
        //Check and Open Database connection
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        if (!Page.IsPostBack)
        {
            //Bind gridview existing records
            bindGridView();

            //DOJ Field
            //Fill Years with current year selected
            for (int i = 2013; i >= 1980; i--)
            {
                ddlYear.Items.Add(i.ToString());
            }
            ddlYear.Items.FindByValue(System.DateTime.Now.Year.ToString()).Selected = true; //set current year as selected

            //Fill Months with current month selected
            for (int i = 1; i <= 12; i++)
            {
                ddlMonth.Items.Add(i.ToString());
            }
            ddlMonth.Items.FindByValue(System.DateTime.Now.Month.ToString()).Selected =true; // Set current month as selected

            //Fill days based on selected month
            FillDays();
        }
    }
    #endregion

    #region "Save employee record"
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string doj = string.Empty;
        //Joining selected Day, month and year to create Date of Joining
       doj = Convert.ToString(ddlDay.SelectedValue + "/" + ddlMonth.SelectedValue + "/" + ddlYear.SelectedValue);
        try
        {
            SqlCommand cmd = new SqlCommand("Insert into Emp_Tb(EmpName,Address,DOJ,Salary) values (@EmpName,@Address,@Doj,@Salary)", con);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@EmpName", SqlDbType.VarChar, 100).Value = txtEmployeeName.Text.Trim();        
            cmd.Parameters.Add("@Address", SqlDbType.VarChar, 500).Value = txtAddress.Text.Trim();  
            cmd.Parameters.Add("@Doj", SqlDbType.VarChar, 50).Value = doj;
            cmd.Parameters.Add("@Salary", SqlDbType.Int).Value = txtSalary.Text.Trim();          
            cmd.ExecuteNonQuery();
           //Clear all controls after saving the record
            Clear_Controls();
            //Bind gridview after saving the record
            bindGridView();
        }
        catch (Exception ex)
        { 
            // Show error occurred in message box using JavaScript
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(),Guid.NewGuid().ToString(), "alert('" + ex.Message.ToString() + "');", true);
        }
        finally
        {
            doj = string.Empty;
            //close the database connection
            con.Close();
        }
    }
    #endregion

    #region "Bind gridview with data"
    public void bindGridView()
    {     
            try
            {
                SqlCommand cmd = new SqlCommand("select * from Emp_Tb", con);
                SqlDataAdapter adp = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adp.Fill(ds);
              
                if (ds.Tables[0].Rows.Count > 0)
                {                  
                    grdEmp.DataSource = ds;
                    grdEmp.DataBind();
                }
                else
                {  
                    //Bind Empty grdview with Columns names in Header and "No employee record found" message if no records are found in the database
                    BindEmptyGridWithHeader(grdEmp, ds);
                }
            }
            catch (Exception ex)
            {              
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(),Guid.NewGuid().ToString(), "alert('" + ex.Message.ToString() + "');", true);
            }
            finally
            {               
                con.Close();
            }    
           }   
    #endregion
   
    #region "paging in gridview"
    protected void grdEmp_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdEmp.PageIndex = e.NewPageIndex;
        //Call bind gridview function
        bindGridView();
    }
    #endregion

    #region "Cancel code in gridview"
    protected void grdEmp_RowCancelingEdit(object sender, GridViewCancelEditEventArgse)
    {
        grdEmp.EditIndex = -1;
        bindGridView();
    }
    #endregion

    #region "Deletion in gridview"
    protected void grdEmp_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            int empId = Convert.ToInt32(grdEmp.DataKeys[e.RowIndex].Value);
            SqlCommand cmd = new SqlCommand("delete from Emp_Tb where Emp_Id_Pk= @EmpId", con);
            cmd.Parameters.Add("@EmpId", SqlDbType.Int).Value = empId;
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            grdEmp.EditIndex = -1;
            bindGridView();
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(),Guid.NewGuid().ToString(), "alert('"+ ex.Message.ToString() +"');", true);
        }
        finally
        {
            con.Close();
        }
    }
    #endregion

    #region "updation in gridview"
    protected void grdEmp_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {    
        string empName = string.Empty;
        string address = string.Empty;
        string dojUpdated = string.Empty;     
        try
        {
            // Finding dropdownlist inside gridview and getting updated value
            DropDownList ddlEditDojYear = (DropDownList)(grdEmp.Rows[e.RowIndex].FindControl("ddlEditYear"));
            DropDownList ddlEditDojMonth = (DropDownList)(grdEmp.Rows[e.RowIndex].FindControl("ddlEditMonth"));
            DropDownList ddlEditDojDay = (DropDownList)(grdEmp.Rows[e.RowIndex].FindControl("ddlEditDay"));

            // creating Updated DOJ field
            dojUpdated = Convert.ToString(ddlEditDojDay.SelectedValue + "/" + ddlEditDojMonth.SelectedValue + "/" + ddlEditDojYear.SelectedValue);
           
            //Read Emp_id_Pk from DataKeyNames
            int empId = Convert.ToInt32(grdEmp.DataKeys[e.RowIndex].Value);
            //Finding TextBox inside gridview and getting updated value
            empName = ((TextBox)(grdEmp.Rows[e.RowIndex].FindControl("txtEmpName"))).Text.Trim();
            address = ((TextBox)(grdEmp.Rows[e.RowIndex].FindControl("txtEditAddress"))).Text.Trim();
            int sal = Convert.ToInt32(((TextBox)(grdEmp.Rows[e.RowIndex].FindControl("txtSal"))).Text.Trim());

            SqlCommand cmd = new SqlCommand("update Emp_Tb set EmpName=@EmpName,Address=@Address,DOJ=@Doj,Salary=@Salary where Emp_Id_Pk=@EmpId", con);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@EmpId", SqlDbType.Int).Value = empId;
            cmd.Parameters.Add("@EmpName", 
...