Edit Jquery DataTable Asp.net c# CRUD operation

/ / 3 Comments

Overview: How to edit jQuery Datatable in asp.net c# using Gridview control, CRUD operation. The purpose of this article is to show how you can implement JQuery DataTables with Asp.net Gridview Control. The jQuery DataTables plugin is an excellent client-side component.

This plugin adds lots of functionalities to the plain HTML tables that are placed in web pages such as  sorting, searching, pagination, changing page length, etc

HTML Markup: Here, in HTML markup, there's a pencil image icon that on click becomes editable and so a user can edit the values and look at class name  .i.e  set class name as update_ + id using `string.Concat()`.   where id is database rowId.
<asp:GridView ID=”myGridview” runat=”server” BackColor=”White” AutoGenerateColumns=”False” CssClass=”gvmyalign”
BorderColor=”Gray” BorderStyle=”Solid” BorderWidth=”1px” CellPadding=”4″ ForeColor=”Black” GridLines=”None” Width=”500px”
AllowPaging=”True” ShowFooter=”false” >
<SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True” ForeColor=”#333333″ />
<HeaderStyle BackColor=”#A86E07″ Font-Bold=”True” ForeColor=”White” />
<Columns>
<asp:TemplateField HeaderText=”Id” Visible=”false”>
<ItemTemplate>
<asp:Label ID=”lblid” runat=”server” Text=’<%# Eval(“Id”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Name” ItemStyle-Width=”230″>
<ItemTemplate>
<asp:Label ID=”lblname” runat=”server” Text=’<%# Eval(“Name”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader=”False” ItemStyle-Width=”90″ >
<ItemTemplate>
<asp:Image ID=”Image1″ ToolTip=”Edit” style=”cursor:pointer;” CssClass=’ <%# string.Concat(“update_”,Eval(“Id”)) %>’ ImageUrl=”~/images/pencil.png” runat=”server” />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor=”#A86E07″ ForeColor=”White” HorizontalAlign=”Center” />
<EditRowStyle BackColor=”#d9d9d9″ />
<AlternatingRowStyle BackColor=”White” ForeColor=”#A86E07″ />
</asp:GridView>
 
Code Behind: You need to add `Page_PreRender` event on .cs  where we set gridview’s `UseAccessibleHeader=true `
protected void (object sender, EventArgs e)
{
if (myGridview.Rows.Count > 0) {
myGridview.UseAccessibleHeader = true;
myGridview.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}

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

public void gvBind() {
myGridview.EmptyDataText = "No Record";
DataTable dt = getData();
myGridview.DataSource = dt;
myGridview.DataBind();

}

Now the Real coding part comes here using JQuery Data tables. Add JqueryDatable Script Files Now after applying JQuery DataTable, our Asp.net  Gridview control look like the below image.

DefaultMode : Editable jquery datatable sp.net c#  

Edit Mode: on click edit icon makes Jquery datatable edit mode


Edit Row:  On Click of pencil image we convert `Lable` into `Textboxes` and place it inside JQuery Datatables which we stored using variable `oTable`. Here on EDIT mode we replace pencil image with SAVE and CANCEL image button, also set respected Ids into classes as same we did for pencil image. On cancel image click we undo edit mode, when the user finishes editing and clicks the Save image button an AJAX call is sent to the server-side page that updates the records into the database. Also you need to check some JQuery Datatables method which have used like `fnUpdate()` , ` fnDraw()` , ` fnGetData(nRow)`

Client-side code performing jQuery data table edit, update, insert functionality:

var oTable;

function editRow(oTable, nRow) {
  var aData = oTable.fnGetData(nRow);
  var jqTds = $('>td', nRow);
  var gtval = aData[1];
  var absValue = $("#hdid").val();
  var mySav_Class = absValue.replace('update_', 'sav_');
  var myCnl_Class = absValue.replace('update_', 'cnl_');
  var sname = $("#hdname").val();

  jqTds[0].innerHTML = '<input class="edt1" type="text" value="' + sname + '">';
  jqTds[1].innerHTML = '<img class="' + mySav_Class + '" title="Save" src="save.png" /><img class="' + myCnl_Class + '" title="Cancel" src="cancle.png" />';
}

function restoreRow(oTable, nRow) {
  var aData = oTable.fnGetData(nRow);
  var jqTds = $('>td', nRow);
  for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
    oTable.fnUpdate(aData[i], nRow, i, false);
  }
  oTable.fnDraw();
}

function updatevalidDatarow() {
  if ($('.edt1').val() == "") {
    alert("Enter name.");
    return false
  }
  return true;
}
 
$(document).ready(function() {

  //One Pencil Img click make it editable mode
  var nEditing = null;
  $("img[class^='update_']").live('click', function(event) {
    event.preventDefault;
    var getId = $(this).attr("class");
    $("#hdid").val(getId); // hdid is hidden field
    var nRow = $(this).parents('tr')[0];
    var setName = $.trim($(this).closest('tr').find('td').eq(0).text());
    $("#hdname").val(setName); // hdname is hidden field

    if (nEditing !== null && nEditing != nRow) {
      restoreRow(oTable, nEditing);
      editRow(oTable, nRow);
      nEditing = nRow;
    } else {
      editRow(oTable, nRow);
      nEditing = nRow;
    }
  });

  //On cancle Img click undo editable mode ie not editable
  $("img[class^='cnl_']").live('click', function(event) {
    var abc = $(this).attr("class");
    var datetxt = $("#hdname").val();
    $('.edt1').replaceWith(datetxt);
    var arr = [];
    arr = abc.split('_');
    var id = arr[1];
    var updateclass = "update_" + id;
    var updatebtn = '<img src="pencil.png" style="cursor:pointer;" title="Edit" class="' + updateclass + '">';
    $('.' + abc).replaceWith(updatebtn);
    $('.sav_' + id).replaceWith("");
  });
  //On save Img Click update Query fire and saves the record into database.
  $("img[class^='sav_']").live('click', function(event) {
    var s = $(this).attr('class');
    var arr = [];
    arr = s.split('_');
    var id = arr[1];
    var updateclass = "update_" + id;
    var updatebtn = '<img src="pencil.png" title="Edit" style="cursor:pointer;" class="' + updateclass + '">';
    var upName = $(".edt1").val();
    var dataString = id + "=" + upName;
    var nposition = $(this).closest("td").get(0);
    var aPosition = oTable.fnGetPosition(nposition);

    if (updatevalidDatarow()) {

      $.ajax({
        type: "POST",
        url: "ajax_function/updatefn.asmx/updateName",
        data: "{ 'prefix': '" + dataString + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
          var success = data.d;
          if (success == "Record Updated") {
            alertify.alert("Record is updated successfully.");
            $('.edt1').replaceWith(upName);
            $('.' + s).replaceWith(updatebtn);
            $('.cnl_' + id).replaceWith("");
            nEditing = null;
            oTable.fnUpdate(upName, aPosition[0], 0, false);
            oTable.fnDraw();
          }
        },
        error: OnErrorCall
      });
    }
  });

  function OnErrorCall(response) {
    alert(response.statusText);
  }

  $(".gvmyalign span").contents().unwrap();
  oTable = $(".gvmyalign").dataTable({
    "bJQueryUI": true,
    "sPaginationType": "full_numbers"

  });
});

 Server Side:- Add a webserivce file named as updatefn.asmx

In updatefn.asmx we have a WebMethod  updateName(), which fires Update query and return result status. which we will display as the resulting message on ajax call of success.

[WebMethod]
public string[] updateName(string prefix) {
  List d = new List();
  string resultmessage = "";
  string[] value = prefix.Split('=');
  int update_id = Convert.ToInt32(value[0]);
  string update_name = value[1];
  int result = updateIndustry_Query(update_id, update_name);
  if (result > 0) {
    resultmessage = "Record Updated";
  }

  d.Add(string.Format("{0}", resultmessage));
  return d.ToArray();
}

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

3 Comments

  1. Vijay 12/04/2014 09:51:37
    Please send me the source code of Edit Jquery DataTable Asp.net c# CRUD operation