Pages

21 Aug 2013

How to write Xml file programmatically with ASP.NET XmlWriter

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Xml" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e)
    {
        string xmlFile = Request.PhysicalApplicationPath + @"App_Data\BookStore.xml";
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.ConformanceLevel = ConformanceLevel.Auto;
        settings.OmitXmlDeclaration = false;
        try
        {
            using (XmlWriter writer = XmlWriter.Create(xmlFile, settings))
            {
                writer.WriteStartDocument(false);
                writer.WriteComment("This is a comment.");
                writer.WriteStartElement("books");
                writer.WriteStartElement("book");
                writer.WriteElementString("id","1");
                writer.WriteElementString("name", "Apple Training Series: GarageBand 09");
                writer.WriteElementString("author", "Mary Plummer");
                writer.WriteElementString("price","$39.99");
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.Flush();
                Label1.Text = "File written successfully!";
                }
            }
        catch (Exception ex)
        {
            Label1.Text = "An Error Occured: " + ex.Message;
        }
    }
</script>
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>XmlWriter: How to write Xml file programmatically in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy; font-style:italic;">XML Example: Writing Xml File Programmatically</h2>
        <asp:Label  
             ID="Label1"
             runat="server"
             Font-Bold="false"
             ForeColor="PaleVioletRed"
             Font-Size="Large"
             Font-Names="Comic Sans MS"
             >
        </asp:Label>
    </div>
    </form>
</body>
</html>  

20 Aug 2013

Example of gridview rowcommand on Button Click

One of the most used controls in my projects is Gridview. Therefore, I thought of writing a tip which has been used in my projects frequently.

Gridview displays the value of a data source in a table. Here, I am going to give an example of using an event called "RowCommand". The RowCommand is raised when a button, LinkButton or ImageButton is clicked in the Gridview Control.


The HTML part of the gridview is:

asp:GridView ID="gridMembersList"
AutoGenerateColumns="False" GridLines="None"
            runat="server"
            onrowcommand="gridMembersList_RowCommand">
        <Columns>
        <asp:TemplateField HeaderText="User Name">
        <ItemTemplate>
            <asp:Literal ID="ltrlName" runat="server"
            Text='<%# Eval("Name") %>'></asp:Literal>
            <asp:Literal ID="ltrlSlno" runat="server" Visible="False"
                Text='<%# Eval("Id") %>'></asp:Literal>
        </ItemTemplate>
        </asp:TemplateField>
     
        <asp:TemplateField HeaderText="View More">
        <ItemTemplate>
            <asp:Button ID="btnViewmore"
            CommandArgument="<%# ((GridViewRow) Container).RowIndex %>
            " CommandName="More" runat="server" Text="View More" />
        </ItemTemplate>
        </asp:TemplateField>
        </Columns>

        </asp:GridView>


In the HTML part , I have binded the values which have to be displayed on the page.

And in the code behind, I have used an XML to load the data to the gridview. When the button is clicked, the event verifies for the command name and command argument.

And, then, I have just alerted the name of the user in this example. Changes can be made according to the requirement.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string pathofxml = Server.MapPath("xml/MemberDetails.xml");
            DataSet ds = new DataSet();
            ds.ReadXml(pathofxml);
            gridMembersList.DataSource = ds;
            gridMembersList.DataBind();
        }
    }


protected void gridMembersList_RowCommand(object sender, GridViewCommandEventArgs e)
   {
        if (e.CommandName == "More")
        {
            int index = Convert.ToInt32(e.CommandArgument.ToString());
            Literal ltrlslno = (Literal)gridMembersList.Rows[index].FindControl("ltrlSlno");
            Literal ltrlName = (Literal)gridMembersList.Rows[index].FindControl("ltrlName");
            ScriptManager.RegisterStartupScript(this, this.GetType(),
            "Message", "alert('" + ltrlName.Text+ "');", true);
        }
    }


I hope this will be helpful for the beginner.

19 Aug 2013

Get id of focussed control with Jquery, asp,net, html

get id of focussed control id use the jquery selector "addClass" and "removeClass" with jquery

$('#txtkeyboard').focus(function() {
$(this).addClass("focus");
$('#txtpassword').removeClass("focus");
});

$('#txtpassword').focus(function() {
$(this).addClass("focus");
$('#txtkeyboard').removeClass("focus");
});

get control id - use this code

var focused = $('.focus').attr("id");
alert(focused);

Checking for uppercase, lowercase, numbers with Jquery

var upperCase= new RegExp('[^A-Z]');
var lowerCase= new RegExp('[^a-z]');
var numbers = new RegExp('[^0-9]');

if(!$(this).val().match(upperCase) && !$(this).val().match(lowerCase) && !$(this).val().match(numbers))  
{
    $("#passwordErrorMsg").html("Your password must be between 6 and 20 characters. It must contain a mixture of upper and lower case letters, and at least one number or symbol.");
}
else
{
    $("#passwordErrorMsg").html("OK")
}


Use the checkbox control


var jIsHasKids = $('#chkIsHasKids').attr('checked').toLowerCase();

get its value as lowercase:

var jIsHasKids = $('#chkIsHasKids:checked').val().toLowerCase();

you can render the text as upper or lower case in pure CSS, without any Javascript using the text-transform property:


.myclass {
    text-transform: lowercase;
}

try this


var jIsHasKids = $('#chkIsHasKids').attr('checked');
jIsHasKids = jIsHasKids.toString().toLowerCase();
//OR
jIsHasKids = jIsHasKids.val().toLowerCase();

Asp.net, Jquery, HTML- Online virtual keyboard with jquery

<script type="text/javascript">
   $(document).ready(function() {
       $('#remember').live('click', function() {
           $('#txtkeyboard').focus(function() {
               $(this).addClass("focus");
               $('#txtpassword').removeClass("focus");
           });

           $('#txtpassword').focus(function() {
               $(this).addClass("focus");
               $('#txtkeyboard').removeClass("focus");
           });

           var isChecked = $('#remember:checked').val() ? true : false;

           if (isChecked == true) {
               var count = $('#tblkeyboard').find('tr td').length;
               $('#tblkeyboard').css("font-weight", "bold");
               $('#tblkeyboard tr td').click(function() {
                   var username = $(this).text().trim();
                   if (username == 'CLEAR') {
                       $('#txtkeyboard').val('');
                       $('#txtpassword').val('');
                       return;
                   }
                   else if (username == 'CAPS LOCK') {
                       for (i = 0; i < count; i++) {
                           var ss = $('#tblkeyboard').find('td:eq(' + i + ')').text();
                           if (i == 65 || i == 66) { return; }
                           var iscap = false;
                           if (/[a-zA-Z]/.test(ss) == true) {
                               var uppercase = new RegExp('[A-Z]');
                               var lowercase = new RegExp('[a-z]');
                               if (ss.match(uppercase)) {
                                   iscap = true;
                               }
                               if (ss.match(lowercase)) {
                                   iscap = false;
                               }
                               if (iscap == false) {
                                   $('#tblkeyboard').find('td:eq(' + i + ')').text(ss.toUpperCase());
                               }
                               if (iscap == true) {
                                   $('#tblkeyboard').find('td:eq(' + i + ')').text(ss.toLowerCase());
                               }
                           }
                       }

                   }
                   else {
                       var focused = $('.focus').attr("id");
                       //alert(focused);
                       var a = $('#' + focused).val();
                       //alert(a + '   ' + username);
                       $('#' + focused).val(a + username);
                   }
               });
           } else { location.reload(true); return; }
       })
   })
 
</script>

HTML Script

<div class="row-fluid" align="center">
<div class="well span5 left login-box">
<div class="alert alert-info">
Please login with your Username and Password.
</div>
<div class="form-horizontal" >
<fieldset>
<div class="input-prepend" title="Username" data-rel="tooltip">
<span class="add-on"><i class="icon-user"></i></span>

                                <asp:TextBox ID="txtkeyboard" class="input-large span10" Text="admin"
                                    runat="server" Width="300px">admin</asp:TextBox>
</div>
<div class="clearfix"></div>

<div class="input-prepend" title="Password" data-rel="tooltip">
<span class="add-on"><i class="icon-lock"></i></span>

<asp:TextBox ID="txtpassword" class="input-large span10" Text="admin123456"
                                    runat="server" TextMode="Password" Width="300px"></asp:TextBox>
</div>
<div class="clearfix"></div>

<div class="input-prepend">
<label class="remember" for="remember"><input type="checkbox" id="remember" />Enable Virtual Keyboard</label
</div>
<div class="clearfix"></div>

<p class="center span5">

                            <asp:Button ID="btnLogin" class="btn btn-primary" runat="server" Text="Login"
                                    Width="80px" onclick="btnLogin_Click" />
</p>
</fieldset>

</div>
</div><!--/span-->
<div class="well span5 left login-box">
   <div class="alert alert-info">
Online Virtual Keyboard
</div>
<table id="tblkeyboard" class="style1">
                <tr>
                    <td >
                        ~</td>
                    <td>
                        !</td>
                    <td>
                        @</td>
                    <td>
                        #</td>
                    <td>
                        $</td>
                    <td>
                        %</td>
                    <td>
                        ^</td>
                    <td>
                        &amp;</td>
                    <td>
                        *</td>
                    <td>
                        (</td>
                    <td>
                        )</td>
                    <td>
                        _</td>
                    <td>
                        +</td>
                </tr>
                <tr>
                    <td>
                        `</td>
                    <td>
                        1</td>
                    <td>
                        2</td>
                    <td>
                        3</td>
                    <td>
                        4</td>
                    <td>
                        5</td>
                    <td>
                        6</td>
                    <td>
                        7</td>
                    <td>
                        8</td>
                    <td>
                        9</td>
                    <td>
                        0</td>
                    <td>
                        -</td>
                    <td>
                        =</td>
                </tr>
                <tr>
                    <td>
                        q</td>
                    <td>
                        w</td>
                    <td>
                        e</td>
                    <td>
                        r</td>
                    <td>
                        t</td>
                    <td>
                        y</td>
                    <td>
                        u</td>
                    <td>
                        i</td>
                    <td>
                        o</td>
                    <td>
                        p</td>
                    <td>
                        {</td>
                    <td>
                        }</td>
                    <td>
                        |</td>
                </tr>
                <tr>
                    <td>
                        a</td>
                    <td>
                        s</td>
                    <td>
                        d</td>
                    <td>
                        f</td>
                    <td>
                        g</td>
                    <td>
                        h</td>
                    <td>
                        j</td>
                    <td>
                        k</td>
                    <td>
                        l</td>
                    <td>
                        [</td>
                    <td>
                        ]</td>
                    <td>
                        \</td>
                    <td>
                        /</td>
                </tr>
                <tr>
                    <td>
                        z</td>
                    <td>
                        x</td>
                    <td>
                        c</td>
                    <td>
                        v</td>
                    <td>
                        b</td>
                    <td>
                        n</td>
                    <td>
                        m</td>
                    <td>
                        &lt;</td>
                    <td>
                        &gt;</td>
                    <td>
                        ;</td>
                    <td>
                        :</td>
                    <td>
                        &#39;</td>
                    <td>
                        &quot;</td>
                </tr>
                <tr>
                    <td colspan="5">
                    CAPS LOCK </td>
                    <td colspan="5">
                       CLEAR</td>
                    <td>
                        ,</td>
                    <td>
                        ?</td>
                    <td>
                        .</td>
                </tr>
            </table>
</div>
</div>



16 Aug 2013

Beginner PHP Tutorial With Videos


Beginner PHP Tutorial - 1 - Introduction to PHP



Beginner PHP Tutorial - 2 - Introduction to PHP





Beginner PHP Tutorial - 3 - Introduction to PHP


Beginner PHP Tutorial -4 - Introduction to PHP



Beginner PHP Tutorial -5 - Introduction to PHP




Beginner PHP Tutorial -6 - Introduction to PHP


Beginner PHP Tutorial -6 - Introduction to PHP



Beginner PHP Tutorial -7 - Introduction to PHP




Beginner PHP Tutorial -8- Introduction to PHP


Beginner PHP Tutorial -9- Introduction to PHP


What is PHP?

What is PHP?

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

Nice, but what does that mean? An example:

Example #1 An introductory example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Example</title>
    </head>
    <body>

        <?php
            echo "Hi, I'm a PHP script!";
        ?>

    </body>

</html>



Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (in this case, output "Hi, I'm a PHP script!"). The PHP code is enclosed in special start and end processing instructions <?php and ?> that allow you to jump into and out of "PHP mode."

What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. You can even configure your web server to process all your HTML files with PHP, and then there's really no way that users can tell what you have up your sleeve.

The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours.


Although PHP's development is focused on server-side scripting, you can do much more with it. Read on, and see more in the What can PHP do? section, or go right to the introductory tutorial if you are only interested in web programming.


12 Aug 2013

Asp.net Link Button With POP Up code

Example

<ItemTemplate>
<a href="javascript:ShowPopup(<%# Eval("AutoId") %>)">Show Details</a>
</ItemTemplate>


Javascript Code

<script type="text/javascript">
        function ShowPopup(id) {
            window.open('ShowDetails.aspx?id=' + id, "showdetails", "scrollbars=no,resizable=no,width=400,height=280");
        }
</script>

10 Aug 2013

JQuery form validations example in asp.net

html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Show Inline validation Messages</title>
<link href="css/template.css" rel="stylesheet" type="text/css" />
<link href="css/validationEngine.jquery.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.6.min.js" type="text/javascript"></script>
<script src="js/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#form1").validationEngine();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table align="center">
<tr>
<td colspan="2">
<div style="border: 1px solid #CCCCCC; padding: 10px;">
<table cellpadding="0" cellspacing="30" style=" background-color:White">
<tr>
<td>First Name:</td>
<td><asp:TextBox ID="txtfname"  runat="server" CssClass="validate[required]"/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><asp:TextBox ID="txtlname"  runat="server" CssClass="validate[required]"/></td>
</tr>
<tr >
<td>Email:</td>
<td><asp:TextBox ID="txtemail" runat="server"  CssClass="validate[required,custom[email]" />
</td>
</tr>
<tr >
<td>Url:</td>
<td><asp:TextBox ID="txtUrl" runat="server" CssClass="validate[required,custom[url]] text-input" />
</td>
</tr>
<tr>
<td valign="top">Address:</td>
<td>
<asp:TextBox ID="txtaddress" runat="server" TextMode="MultiLine" Rows="8" Columns="26"/></td>
</tr>
<tr>
<td>State:</td>
<td>
<asp:DropDownList ID="ddlState" runat="server" CssClass="validate[required] radio">
<asp:ListItem value="">Choose State</asp:ListItem>
<asp:ListItem Value="AL">Alabama</asp:ListItem>
<asp:ListItem value="AK">Alaska</asp:ListItem>
<asp:ListItem  value="AL">Alabama </asp:ListItem>
<asp:ListItem  value="AK">Alaska</asp:ListItem>
<asp:ListItem  value="AZ">Arizona</asp:ListItem>
<asp:ListItem  value="AR">Arkansas</asp:ListItem>
<asp:ListItem  value="CA">California</asp:ListItem>
<asp:ListItem  value="CO">Colorado</asp:ListItem>
<asp:ListItem  value="CT">Connecticut</asp:ListItem>
<asp:ListItem  value="DE">Delaware</asp:ListItem>
<asp:ListItem  value="FL">Florida</asp:ListItem>
<asp:ListItem  value="GA">Georgia</asp:ListItem>
<asp:ListItem  value="HI">Hawaii</asp:ListItem>
<asp:ListItem  value="ID">Idaho</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>Zip:</td>
<td>
<asp:TextBox ID="txtZip" runat="server" CssClass="validate[required,custom[integer]] text-input"/>
</td>
</tr>
<tr>
<td> I Agree Conditions</td>
<td>
<input class="validate[required] checkbox" type="checkbox" id="agree" name="agree"/>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblResult" runat="server" Font-Bold="true"/>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>

DEMO





Read XML file with jQuery

<?xml version="1.0" encoding="utf-8" ?>
<books>
    <book title="CSS Mastery" imageurl="images/css.jpg">
    <description>
    info goes here.
    </description>
    </book>

    <book title="Professional ASP.NET" imageurl="images/asp.jpg">
    <description>
    info goes here.
    </description>
    </book>

    <book title="Learning jQuery" imageurl="images/lj.jpg">
    <description>
    info goes here.
    </description>
    </book>
</books>


$(document).ready(function()
      {
        $.get('myData.xml', function(d){
        $('body').append('<h1> Recommended Web Development Books </h1>');
        $('body').append('<dl>');
 
        $(d).find('book').each(function(){
 
            var $book = $(this);  
            var title = $book.attr("title");
            var description = $book.find('description').text();
            var imageurl = $book.attr('imageurl');
 
            var html = '<dt> <img class="bookImage" alt="" src="' + imageurl + '" /> </dt>';
            html += '<dd> <span class="loadingPic" alt="Loading" />';
            html += '<p class="title">' + title + '</p>';
            html += '<p> ' + description + '</p>' ;
            html += '</dd>';
 
            $('dl').append($(html));
             
            $('.loadingPic').fadeOut(1400);
        });
    });
});



Jquery Datetime format, Get month, Day, Time

Get month name instead of number

var months = [ "January", "February", "March", "April", "May", "June",
               "July", "August", "September", "October", "November", "December" ];

var selectedMonthName = months[$("#datepicker").datepicker('getDate').getMonth()];

var monthName = $.datepicker.formatDate('MM', $("#datepicker").datepicker('getDate'));



Other example

Date.prototype.getMonthName = function(lang) {
    lang = lang && (lang in Date.locale) ? lang : 'en';
    return Date.locale[lang].month_names[this.getMonth()];
};

Date.prototype.getMonthNameShort = function(lang) {
    lang = lang && (lang in Date.locale) ? lang : 'en';
    return Date.locale[lang].month_names_short[this.getMonth()];
};

Date.locale = {
    en: {
       month_names: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
       month_names_short: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    }

};


One Another Example

Date.prototype.monthNames = [
    "January", "February", "March",
    "April", "May", "June",
    "July", "August", "September",
    "October", "November", "December"
];

Date.prototype.getMonthName = function() {
    return this.monthNames[this.getMonth()];
};
Date.prototype.getShortMonthName = function () {
    return this.getMonthName().substr(0, 3);
};

// usage:
var d = new Date();
alert(d.getMonthName());      // "October"

alert(d.getShortMonthName()); // "Oct"

3 Aug 2013

Select, Update, and Delete Data in a ASP.NET GridView Control.

In this article, I will show you how to use an ASP.NET 2.0 GridView control to Select, update, and delete data in a SQL database.

We will use SQL Client data provider to provide database connectivity.

Before you can use any classes related to SQL Client data adapter, we need to import the SqlClient namespace in your application by using the following using statement.

using System.Data.SqlClient;

Next, we need to define the database connection string.

The below is my connection string which is stored in web.config file. You can change this connection string according to your SQL server database setting. I am storing my database file in App_Data folder. If you want use my database file then attach that file.

<appSettings>

<add key="connect" value="Initial Catalog=Data; Data Source=DHARMENDRA\SQLSERVER2005; uid=sa; pwd=wintellect"/>

</appSettings>



The following code snippet shows how to connect to a database and create other database access related objects.

    SqlDataAdapter da;

    SqlConnection con;

    DataSet ds = new DataSet();

    SqlCommand cmd = new SqlCommand();

This function is use to fetch data from the StudentRecord table, fills data in a DataTable object and find it to a GridView control using the DataSource property. In the end, the code calls the GridView.DataBind method to apply the binding.



public void BindData()

{

        con = new     SqlConnection(ConfigurationSettings.AppSettings["connect"]);

        cmd.CommandText = "Select * from StudentRecord";

        cmd.Connection = con;

        da = new SqlDataAdapter(cmd);

        da.Fill(ds);

        con.Open();

        cmd.ExecuteNonQuery();

        GridView1.DataSource = ds;

        GridView1.DataBind();

        con.Close();

 }

Now on the page load method, we call the FillStudentRecordGrid method.



protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack)

        {

            BindData();

        }

    }

Now, next step is to set the GridView control settings.

The ASP.NET code for the DataView control. In this code below code, you see database table columns binding with the bound fields and formatting is provided using the template fields. If you are using my database, just copy and paste the code or use the attached application. If you are using your database, you need to replace column binding with your database table columns.

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



<!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>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <asp:GridView ID="GridView1" runat="server" PageSize="3" AutoGenerateColumns="false"

AllowPaging="true"

BackColor="White"

BorderColor="#CC9966"

BorderStyle="None"              

BorderWidth="1px"

CellPadding="4"

OnRowEditing="GridView1_RowEditing"

OnRowUpdating="GridView1_RowUpdating"

OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"

OnRowDeleting="GridView1_RowDeleting">

<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />

<RowStyle BackColor="White" ForeColor="#330099" />

<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" /> <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center"/>

<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />

<Columns>

<asp:TemplateField HeaderText="StId">

<ItemTemplate>

<asp:Label ID="lblstid" runat="server" Text='<%#Eval ("stId")%>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Name">

<ItemTemplate>

<asp:TextBox ID="txtName" runat="server" Text='<%#Eval("name")%>'> </asp:TextBox>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="ClassName">

<ItemTemplate>

<asp:TextBox ID="txtClassName" runat="server" Text='<%#Eval ("Classname") %>'></asp:TextBox>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="RollNo">

<ItemTemplate>

<asp:TextBox ID="txtRollNo" runat="server" Text='<%#Eval ("rollno")%>'> </asp:TextBox>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="EmailId">

<ItemTemplate>

<asp:TextBox ID="txtEmailId" runat="server" Text='<%#Eval ("emailId")%>'> </asp:TextBox>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Edit" ShowHeader="false">

<EditItemTemplate>

<asp:LinkButton ID="lnkbtnUpdate" runat="server" CausesValidation="true" Text="Update" CommandName="Update"></asp:LinkButton>

<asp:LinkButton ID="lnkbtnCancel" runat="server" CausesValidation="false" Text="Cancel" CommandName="Cancel"></asp:LinkButton>

</EditItemTemplate

<ItemTemplate>

<asp:LinkButton ID="btnEdit" runat="server" CausesValidation="false" CommandName="Edit" Text="Edit"></asp:LinkButton>

</ItemTemplate>

</asp:TemplateField>

<asp:CommandField HeaderText="Delete" ShowDeleteButton="true" ShowHeader="true" />

<asp:CommandField HeaderText="Select" ShowSelectButton="true" ShowHeader="true" />

</Columns>

</asp:GridView

<table>

<tr>

<td>

<asp:Label ID="lblName" runat="server" Text="Name"></asp:Label>

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

</td>

<td>

<asp:Label ID="lblClassName" runat="server" Text="ClassName"></asp:Label>

<asp:TextBox ID="txtClassName" runat="server"></asp:TextBox>

</td>

<td>

<asp:Label ID="lblRollNo" runat="server" Text="RollNo"></asp:Label>

<asp:TextBox ID="txtRollNo" runat="server"></asp:TextBox>

</td>

<td>

<asp:Label ID="lblEmailId" runat="server" Text="EmailId"></asp:Label> <asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox>

</td>

<td>

<asp:Label ID="lblTotalRecord" runat="server" Text="TotalRecord"></asp:Label>

<asp:TextBox ID="txtTotalRecord" runat="server"></asp:TextBox>

</td>

</tr>

<tr>

<td>

<asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click1"/>

<asp:Button ID="Reset" runat="server" Text="Reset" OnClick="Reset_Click1" />

</td>

</tr>

</table>

</div>

</form>

</body>

</html>

how insert, Edit, Update and delete data in gridview with sqldatasource using asp.net

Design View

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>
</head>
<body>
<form id="form2" runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId" runat="server"
AutoGenerateColumns="false" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
DataSourceID="sqlds" onrowcommand="gvDetails_RowCommand">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" ImageUrl="~/Images/update.jpg" ToolTip="Update" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/Images/Edit.jpg" ToolTip="Edit" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit" runat="server" ImageUrl="~/Images/delete.jpg" ToolTip="Delete" Height="20px" Width="20px" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/AddNewitem.jpg" CommandName="Insert" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:Label ID="lbleditusr" runat="server" Text='<%#Eval("Username") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblitemUsr" runat="server" Text='<%#Eval("UserName") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrusrname" runat="server"/>
<asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="txtftrusrname" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="txtfname" runat="server" Text='<%#Eval("FirstName") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblfname" runat="server" Text='<%#Eval("FirstName") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrfname" runat="server"/>
<asp:RequiredFieldValidator ID="rfvfname" runat="server" ControlToValidate="txtftrfname" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="txtlname" runat="server" Text='<%#Eval("LastName") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbllname" runat="server" Text='<%#Eval("LastName") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrlname" runat="server"/>
<asp:RequiredFieldValidator ID="rfvlname" runat="server" ControlToValidate="txtftrlname" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="txtcity" runat="server" Text='<%#Eval("City") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcity" runat="server" Text='<%#Eval("City") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrcity" runat="server"/>
<asp:RequiredFieldValidator ID="rfvcity" runat="server" ControlToValidate="txtftrcity" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="txtDesg" runat="server" Text='<%#Eval("Designation") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDesg" runat="server" Text='<%#Eval("Designation") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrDesignation" runat="server"/>
<asp:RequiredFieldValidator ID="rfvdesignation" runat="server" ControlToValidate="txtftrDesignation" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqlds" runat="server" ConnectionString="<%$ ConnectionStrings:dbconnection %>"
SelectCommand="Select * from Employee_Details"
InsertCommand="insert into Employee_Details(UserName,FirstName,LastName,City,Designation) values(@UserName,@FirstName,@LastName,@City,@Designation)"
DeleteCommand="delete from Employee_Details where UserId=@UserId"
UpdateCommand="update Employee_Details set FirstName=@FirstName,LastName=@LastName, City=@City,Designation=@Designation where UserId=@UserId">
<UpdateParameters>
<asp:Parameter Name="UserId" Type= "Int32" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="City" Type="String" />
<asp:Parameter Name="Designation" Type="String" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="UserName" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="City" Type="String" />
<asp:Parameter Name="Designation" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
</div>
<div>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</div>
</form>
</body>

</html>



Code View

protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Insert")
{
TextBox txtusername = (TextBox)gvDetails.FooterRow.FindControl("txtftrusrname");
TextBox txtfirstname = (TextBox)gvDetails.FooterRow.FindControl("txtftrfname");
TextBox txtlastname = (TextBox)gvDetails.FooterRow.FindControl("txtftrlname");
TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl("txtftrcity");
TextBox txtDesgnation = (TextBox)gvDetails.FooterRow.FindControl("txtftrDesignation");
sqlds.InsertParameters["UserName"].DefaultValue = txtusername.Text;
sqlds.InsertParameters["FirstName"].DefaultValue = txtfirstname.Text;
sqlds.InsertParameters["LastName"].DefaultValue = txtlastname.Text;
sqlds.InsertParameters["City"].DefaultValue = txtCity.Text;
sqlds.InsertParameters["Designation"].DefaultValue = txtDesgnation.Text;
sqlds.Insert();
lblresult.Text = txtusername.Text + " Details Inserted Successfully";
lblresult.ForeColor = Color.Green;
}
if (e.CommandName == "Update")
{
GridViewRow gvrow = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
Label lblusername = (Label)gvrow.FindControl("lbleditusr");
TextBox txtfirstname = (TextBox)gvrow.FindControl("txtfname");
TextBox txtlastname = (TextBox)gvrow.FindControl("txtlname");
TextBox txtCity = (TextBox)gvrow.FindControl("txtcity");
TextBox txtDesgnation = (TextBox)gvrow.FindControl("txtDesg");
sqlds.UpdateParameters ["FirstName"].DefaultValue = txtfirstname.Text;
sqlds.UpdateParameters["LastName"].DefaultValue = txtlastname.Text;
sqlds.UpdateParameters["City"].DefaultValue = txtCity.Text;
sqlds.UpdateParameters["Designation"].DefaultValue = txtDesgnation.Text;
sqlds.Update();
lblresult.Text = lblusername.Text + " Details Updated Successfully";
lblresult.ForeColor = Color.Green;
}
if(e.CommandName=="Delete")
{
GridViewRow gvdeleterow = (GridViewRow) ((ImageButton) e.CommandSource).NamingContainer;
Label lblusername = (Label)gvdeleterow.FindControl("lblitemUsr");
lblresult.Text = lblusername.Text + " Details Updated Successfully";
lblresult.ForeColor = Color.Red;
}

}


After that set your database connection in web.config like this

<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>

</connectionStrings >

ASP.NET - How to Paging GridView Data

    <%@ Page Language="C#" %>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     
    <script runat="server">
     
    </script>
     
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>asp.net GridView Paging example: how to Paging GridView Data</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <h2 style="color:Fuchsia">Paging In GridView</h2>
            <asp:SqlDataSource
                 ID="SqlDataSource1"
                 runat="server"
                 ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
                 SelectCommand="SELECT ProductID, ProductName, UnitPrice FROM Products"
                 >
            </asp:SqlDataSource>
            <asp:GridView
                 ID="GridView1"  
                 runat="server"
                 DataSourceID="SqlDataSource1"
                 AutoGenerateColumns="false"
                 BackColor="Snow"
                 ForeColor="DarkMagenta"
                 BorderColor="DimGray"
                 BorderStyle="Dotted"
                 BorderWidth="2"
                 AllowSorting="true"
                 AllowPaging="true"
                 PageSize="5"
                 >
                <Columns>
                    <asp:BoundField SortExpression="ProductID" HeaderText="Product ID" DataField="ProductID" />
                    <asp:BoundField SortExpression="ProductName" HeaderText="Product Name" DataField="ProductName" />
                    <asp:BoundField SortExpression="UnitPrice" HeaderText="Unit Price" DataField="UnitPrice" />
                </Columns>
            </asp:GridView>
        </div>
        </form>
    </body>
    </html>