Edit, Delete, Paging in gridview using Jquery simplemethod Part-1

Klbaiju
Posted by in jQuery category on for Intermediate level | Points: 250 | Views : 25706 red flag
Rating: 5 out of 5  
 2 vote(s)

In this article we shall learn how to delete, edit, paging in gridview using jquery (without page refresh)

Introduction

 
In this article i am going to do a simple method of update, delete and paging in gridview. using jquery ajax method without refreshing the entire page.

Note from Editor: This is perhaps the first effort of writing an article by KLBaiju, so the presentation of this article may not look standard, please bear with it and provide your comment or feedback to KLBaiju to improve. After all we all are learning !

Table creation


create a table testemp1 with fields id, name, department, salary
add some values
then go to visual studio
add a new project then add a gridviw on page  Newgridview.aspx
change the gridview like this

<asp:GridView ID="GridView1"  AutoGenerateColumns="false" runat="server" 
            CellPadding="4" ForeColor="#333333" 
        GridLines="None" RowStyle-CssClass="record" Width="440px">
        <RowStyle BackColor="#EFF3FB" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" Width="270px" />
        <EditRowStyle BackColor="#2461BF" />
        <AlternatingRowStyle BackColor="White" />
         <RowStyle CssClass="record" Width="80px"></RowStyle>
        <Columns >
        
        <asp:TemplateField HeaderText="ID" HeaderStyle-Width="80px"     >
        <ItemTemplate >
        <span id= 'first<%# Eval("ID") %>'   class='text'><%# Eval("ID") %> </span>
        </ItemTemplate>


        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name" HeaderStyle-Width="80px" ItemStyle-Width="270px" >
        <ItemTemplate>
        <span id= 'second<%# Eval("Id") %>'   class='text'><%# Eval("name") %> </span>
        </ItemTemplate>


        </asp:TemplateField>
       
        <asp:TemplateField HeaderText="Department" HeaderStyle-Width="80px"  ItemStyle-Width="270px">
        <ItemTemplate >
        <span id= 'third<%# Eval("Id") %>'   class='text'><%# Eval("dept") %> </span>
        </ItemTemplate>


        </asp:TemplateField>
        <asp:TemplateField HeaderText="Salary"  HeaderStyle-Width="80px" ItemStyle-Width="270px" >
        <ItemTemplate>
        <span id= 'fourth<%# Eval("Id") %>'   class='text'><%# Eval("salary") %> </span>
        </ItemTemplate>


        </asp:TemplateField>
        <asp:TemplateField HeaderText="Edit"  HeaderStyle-Width="80px" ItemStyle-Width="270px">
        <ItemTemplate>
        <input type="button" id=<%# Eval("ID") %> value="Edit" class='btn1' />
        </ItemTemplate>
        </asp:TemplateField>
         <asp:TemplateField HeaderText="Delete" HeaderStyle-Width="80px" ItemStyle-Width="270px" >
        <ItemTemplate>
        <input type="button" id=<%# Eval("ID") %> value="Delete" class='del' />
        </ItemTemplate>
        </asp:TemplateField>
        </Columns>
    </asp:GridView>


below gridview add this
this for editing

<div id="disp" align="center">
  
    <fieldset style=" width:300px;height:100px;  ">
    <input id="Text1" type="text" class='edit' /><br />
    <table>
    <tr><td><label>Name</label></td><td><input id="Text2" type="text" /></td></tr>
    <tr><td><label>Department</label></td><td><input id="Text3" type="text" /></td></tr>
    <tr><td><label>Salary</label></td><td><input id="Text4" type="text" /><br /></td></tr>
    <tr><td><input type="button"  value ="Save" id="btn1"  /></td><td><input type="button"  value ="Cancel" id="btn2" /></td></tr>
    
    </table>
</fieldset></div>


goto .cs page

SqlConnection con = new SqlConnection("Data Source=BAIJU;Initial Catalog=baiju;Integrated Security=True");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

               SqlDataAdapter da = new SqlDataAdapter("select * from testemp1", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();            
            }

        }
 
run the application we get a screen like this




go to design view of Newgridview.aspx
here we are going to write the jquery code

add this style sheet before head tag

<style type="text/css">
    .edit
    {
     display: none;
    }
     .header
    {
        background-color:Gray;
        font-weight:bold;
        color:White;
        text-align:center;
    }
.highlight
{
background-color:blue;
}
   
.hover { background-color: #00f; color: #fff; }
.page{ margin:5px; }
    </style>

<script src="jquerynew.js" type="text/javascript" charset="utf-8"></script> 
     <script type="text/javascript" language="javascript">

 $(document).ready(function() {


//code for paging

 var rows = $('#GridView1').find(' tbody  .record ').length;

             var no_rec_per_page = 3;
             var no_pages = Math.ceil(rows / no_rec_per_page);
             var $pagenumbers = $('<div id="pages"></div>');
             for (i = 0; i < no_pages; i++) {
                 $('<a href="#" class="page">' + (i + 1) + '</a>').appendTo($pagenumbers);
             }
             $pagenumbers.insertAfter('#GridView1');
             $('.page').hover(function() {
                 $(this).addClass('hover');
             }, function() {
                 $(this).removeClass('hover');
             });
             $('#GridView1').find(' tbody .record ').hide();
             var tr = $('#GridView1   tbody  .record  ');
             for (var i = 0; i <= no_rec_per_page - 1; i++) {
                 $(tr[i]).show();
             }
             $('a').click(function(event) {
                 $('#GridView1').find(' tbody .record ').hide();
                 for (i = ($(this).text() - 1) * no_rec_per_page; i <= $(this).text() * no_rec_per_page - 1; i++) {
                     $(tr[i]).show();

                 }
             });
});
</script>

after this coding paging will work 

Editing


 add this code after  $(document).ready(function() {








$('#disp').hide();




             $('.btn1').click(function() {
                 var ID = $(this).attr("id");
                 $('#result').hide();
var pos = $(this).offset();
                 var width = $(this).width();
               
                 $('#disp').css({
                     right: (pos.left + width) + -260 + 'px',
                     top: pos.top - -25 + 'px'
                     // alert(top);
                 });



      















                 var td = $(this).closest('tr').children('td');


                 var sr = td.eq(1).text();

                 var name = td.eq(2).text();
                 var sal = td.eq(3).text();

                 $("#Text1").val(ID);
                 $("#Text2").val(sr);
                 $("#Text3").val(name);
                 $("#Text4").val(sal);

                 $('#disp').show("slow");

             });


this code for displaying edited fields
run the application click edit button
we get like this





this is for display editing field.
for editing we have to add this code

 //code for updation
             $('#btn1').click(function() {
                 $('#result').show();
                 var id = $("#Text1").val();
                 var name = $("#Text2").val();
                 var dept = $("#Text3").val();
                 var sal = $("#Text4").val();

                 var Data = 'id=' + id + '&name=' + name + '&dept=' + dept + '&sal=' + sal;

                 if (name.length > 0 && dept.length > 0 && sal.length > 0) {
                     $.ajax({
                         type: "GET",
                         data: Data,
                         contentType: "text/html; charset=utf-8",
                         url: "NewGridProcess.aspx",
                         success: function(data) {
                             //  alert(data);
                             if (data == "Success") {
                                 $("#second" + id).html(name);
                                 $("#third" + id).html(dept);
                                 $("#fourth" + id).html(sal);
                                 $('#result').html("<b >Updated successfully</b>");
                                 $('#disp').hide();


                             }
                         }

                     });
                 }
                 else {
                     alert("enter fields");
                 }
             });



this is for passing values to another web page NewGridProcess.aspx
so we have to add new web page name it as NewGridProcess.aspx

on .cs page add

SqlConnection con = new SqlConnection("Data Source=BAIJU;Initial Catalog=baiju;Integrated Security=True");
        protected void Page_Load(object sender, EventArgs e)
        {
            string msg;
            string id = Request.QueryString["id"];
            string name = Request.QueryString["name"];
            string dept = Request.QueryString["dept"];
            string sal = Request.QueryString["sal"];
            SqlCommand cmd = new SqlCommand("update testemp1 set name='" + name + "',dept='" + dept + "',salary='" + sal + "' where id='" + id + "'", con);
            try
            {

                con.Open();
                cmd.ExecuteNonQuery();
                msg = "Success";
                Response.Write(msg);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                Response.Write(msg);

            }
            finally 
            {
                con.Close();
            
            }
        }


run the application
change the fields as you want.
data will update and new data will show in gridview without refresh

Deleting


add this code inside

document.ready(function()
$('.del').click(function() {
                 var rid = $(this).attr("id");
                 
                 var trid = $(this).parents(".record");
                
                 var Data = 'id=' + rid;
                 if (confirm("Do you want to delete this record?")) {

                     $.ajax({
                         type: "GET",
                         data: Data,
                         contentType: "text/html; charset=utf-8",
                         url: "Delprocess.aspx",
                         success: function(data) {
                             alert(data);
                             if (data == "Success") {
                                 trid.css("background-color", "blue");
                                 trid.fadeOut(1000, function() {
                                     trid.remove();
                                 });
                             } 
                              }
                     });
                 }

             });


the add a new webpage  Delprocess.aspx

in the .cs page add this code

SqlConnection con = new SqlConnection("Data Source=BAIJU;Initial Catalog=baiju;Integrated Security=True");
        protected void Page_Load(object sender, EventArgs e)
        {
            string msg;
            string id = Request.QueryString["id"];
            SqlCommand cmd = new SqlCommand("delete from testemp1 where id='" + id + "'", con);
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                msg = "Success";
                Response.Write(msg);
            }
            catch (Exception ex)
            {

            }
            finally
            {

                con.Close();
            }
        }



run the application
press delete button

you get this screen




Reference

Thanks for reading, the books i have referred for this article

  1. apress jquery receipes
  2. Sheo Narayan's ebook and 
  3. help from forums of DotNetFunda.com, asp.net etc

hope every one can understand

Regards
K L BAIJU

Page copy protected against web site content infringement by Copyscape

About the Author

Klbaiju
Full Name: kl baiju
Member Level:
Member Status: Member
Member Since: 9/5/2009 12:02:04 AM
Country:



Login to vote for this post.

Comments or Responses

Posted by: Vishvvas on: 7/24/2011 | Points: 25
Nice article and doesn't look like its a first attempt. Kudos.
Posted by: Klbaiju on: 7/27/2011 | Points: 25
thanks vishvas

Login to post response

Comment using Facebook(Author doesn't get notification)