Thursday, November 13, 2014

Jquery Grid Sample Code in C#





Demo Grid View Image
Feature :
Jquery Search
Paging
Export In Excel,Pdf,Copy and Print


Step :1
Put this code in Script Part 


<!-- PACE LOADER - turn this on if you want ajax loading to show (caution: uses lots of memory on iDevices)-->
<script data-pace-options='{ "restartOnRequestAfter": true }' src="js/plugin/pace/pace.min.js"></script>

<!-- Link to Google CDN's jQuery + jQueryUI; fall back to local -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
   if (!window.jQuery) {
       document.write('<script src="js/libs/jquery-2.1.1.min.js"><\/script>');
   }
</script>

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script>
   if (!window.jQuery.ui) {
       document.write('<script src="js/libs/jquery-ui-1.10.3.min.js"><\/script>');
   }
</script>

<!-- IMPORTANT: APP CONFIG -->
<script src="js/app.config.js"></script>

<!-- JS TOUCH : include this plugin for mobile drag / drop touch events-->
<script src="js/plugin/jquery-touch/jquery.ui.touch-punch.min.js"></script>

<!-- BOOTSTRAP JS -->
<script src="js/bootstrap/bootstrap.min.js"></script>

<!-- CUSTOM NOTIFICATION -->
<script src="js/notification/SmartNotification.min.js"></script>

<!-- JARVIS WIDGETS -->
<script src="js/smartwidgets/jarvis.widget.min.js"></script>

<!-- EASY PIE CHARTS -->
<script src="js/plugin/easy-pie-chart/jquery.easy-pie-chart.min.js"></script>

<!-- SPARKLINES -->
<script src="js/plugin/sparkline/jquery.sparkline.min.js"></script>

<!-- JQUERY VALIDATE -->
<script src="js/plugin/jquery-validate/jquery.validate.min.js"></script>

<!-- JQUERY MASKED INPUT -->
<script src="js/plugin/masked-input/jquery.maskedinput.min.js"></script>

<!-- JQUERY SELECT2 INPUT -->
<script src="js/plugin/select2/select2.min.js"></script>

<!-- JQUERY UI + Bootstrap Slider -->
<script src="js/plugin/bootstrap-slider/bootstrap-slider.min.js"></script>

<!-- browser msie issue fix -->
<script src="js/plugin/msie-fix/jquery.mb.browser.min.js"></script>

<!-- FastClick: For mobile devices -->
<script src="js/plugin/fastclick/fastclick.min.js"></script>

<!--[if IE 8]>

<h1>Your browser is out of date, please update your browser by going to www.microsoft.com/download</h1>

<![endif]-->

<!-- Demo purpose only -->
<script src="js/demo.min.js"></script>

<!-- MAIN APP JS FILE -->
<script src="js/app.min.js"></script>

<!-- ENHANCEMENT PLUGINS : NOT A REQUIREMENT -->
<!-- Voice command : plugin -->
<script src="js/speech/voicecommand.min.js"></script>

<!-- SmartChat UI : plugin -->
<script src="js/smart-chat-ui/smart.chat.ui.min.js"></script>
<script src="js/smart-chat-ui/smart.chat.manager.min.js"></script>

<!-- PAGE RELATED PLUGIN(S) -->
<script src="js/plugin/datatables/jquery.dataTables.min.js"></script>
<script src="js/plugin/datatables/dataTables.colVis.min.js"></script>
<script src="js/plugin/datatables/dataTables.tableTools.min.js"></script>
<script src="js/plugin/datatables/dataTables.bootstrap.min.js"></script>
<script src="js/plugin/datatable-responsive/datatables.responsive.min.js"></script>

<script type="text/javascript">

   // DO NOT REMOVE : GLOBAL FUNCTIONS!

   $(document).ready(function () {

       pageSetUp();

       /* // DOM Position key index //
           
                l - Length changing (dropdown)
                f - Filtering input (search)
                t - The Table! (datatable)
                i - Information (records)
                p - Pagination (paging)
                r - pRocessing
                < and > - div elements
                <"#id" and > - div with an id
                <"class" and > - div with a class
                <"#id.class" and > - div with an id and class
               
                Also see: http://legacy.datatables.net/usage/features
                */

       /* BASIC ;*/
       var responsiveHelper_dt_basic = undefined;
       var responsiveHelper_datatable_fixed_column = undefined;
       var responsiveHelper_datatable_col_reorder = undefined;
       var responsiveHelper_datatable_tabletools = undefined;

       var breakpointDefinition = {
           tablet: 1024,
           phone: 480
       };

   


       /* TABLETOOLS */
       $('#datatable_tabletools').dataTable({

           // Tabletools options:
           //   https://datatables.net/extensions/tabletools/button_options
           "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-4'f><'col-sm-6 col-xs-6 hidden-xs'l><'col-sm-6 col-xs-6 hidden-xs'T>r>" +
                           "t" +
                           "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-sm-6 col-xs-12'p>>",
           "oTableTools": {
               "aButtons": [
                        "copy",
                        "csv",
                        "xls",
                           {
                               "sExtends": "pdf",
                               "sTitle": "SmartAdmin_PDF",
                               "sPdfMessage": "SmartAdmin PDF Export",
                               "sPdfSize": "letter"
                           },
                           {
                               "sExtends": "print",
                               "sMessage": "Generated by EdsetGO <i>(press Esc to close)</i>"
                           }
               ],
               "sSwfPath": "js/plugin/datatables/swf/copy_csv_xls_pdf.swf"
           },
           "autoWidth": true,
           "bPaginate": true,
           "bLengthChange": true,
           "bFilter": true,
           "bInfo": true,
                    "iDisplay":true,
           "iDisplayLength": 15,
           "aLengthMenu": [[10, 25,50, 100, -1], [10, 25, 50, 100, "All"]],
           "preDrawCallback": function () {
               // Initialize the responsive datatables helper once.
               if (!responsiveHelper_datatable_tabletools) {
                   responsiveHelper_datatable_tabletools = new ResponsiveDatatablesHelper($('#datatable_tabletools'), breakpointDefinition);
               }
           },
           "rowCallback": function (nRow) {
               responsiveHelper_datatable_tabletools.createExpandIcon(nRow);
           },
           "drawCallback": function (oSettings) {
               responsiveHelper_datatable_tabletools.respond();
           }
       });

       /* END TABLETOOLS */

   })

   //$(document).ready(function () {
   //    $('#example').DataTable({
   //        dom: 'T<"clear">lfrtip',
   //        tableTools: {
   //            "sSwfPath": "../swf/copy_csv_xls_pdf.swf"
   //        }
   //    });
   //});

</script>

<!-- Your GOOGLE ANALYTICS CODE Below -->
<script type="text/javascript">
   var _gaq = _gaq || [];
   _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
   _gaq.push(['_trackPageview']);

   (function () {
       var ga = document.createElement('script');
       ga.type = 'text/javascript';
       ga.async = true;
       ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
       var s = document.getElementsByTagName('script')[0];
       s.parentNode.insertBefore(ga, s);
   })();
</script>



Step 2 :
C# Code : Put this code in .Aspx File  



<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="Edsetgo.WebForm3" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
   
    <link rel="stylesheet" type="text/css" media="screen" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" media="screen" href="css/font-awesome.min.css">

<!-- SmartAdmin Styles : Caution! DO NOT change the order -->
<link rel="stylesheet" type="text/css" media="screen" href="css/smartadmin-production-plugins.min.css">
<link rel="stylesheet" type="text/css" media="screen" href="css/smartadmin-production.min.css">
<link rel="stylesheet" type="text/css" media="screen" href="css/smartadmin-skins.min.css">

<!-- SmartAdmin RTL Support -->
<link rel="stylesheet" type="text/css" media="screen" href="css/smartadmin-rtl.min.css"> 

<!-- We recommend you use "your_style.css" to override SmartAdmin
    specific styles this will also ensure you retrain your customization with each SmartAdmin update.
<link rel="stylesheet" type="text/css" media="screen" href="css/your_style.css"> -->

<!-- Demo purpose only: goes with demo.js, you can delete this css when designing your own WebApp -->
<link rel="stylesheet" type="text/css" media="screen" href="css/demo.min.css">

<!-- FAVICONS -->
<link rel="shortcut icon" href="img/favicon/favicon.ico" type="image/x-icon">
<link rel="icon" href="img/favicon/favicon.ico" type="image/x-icon">

<!-- GOOGLE FONT -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,300,400,700">
    
<!-- Specifying a Webpage Icon for Web Clip 
Ref: https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html -->
<link rel="apple-touch-icon" href="img/splash/sptouch-icon-iphone.png">
<link rel="apple-touch-icon" sizes="76x76" href="img/splash/touch-icon-ipad.png">
<link rel="apple-touch-icon" sizes="120x120" href="img/splash/touch-icon-iphone-retina.png">
<link rel="apple-touch-icon" sizes="152x152" href="img/splash/touch-icon-ipad-retina.png">
<!-- iOS web-app metas : hides Safari UI Components and Changes Status Bar Appearance -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<!-- Startup image for web apps -->
<link rel="apple-touch-startup-image" href="img/splash/ipad-landscape.png" media="screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape)">
<link rel="apple-touch-startup-image" href="img/splash/ipad-portrait.png" media="screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait)">
<link rel="apple-touch-startup-image" href="img/splash/iphone.png" media="screen and (max-device-width: 320px)">

    
    <%--<script src="media/js/jquery.js"></script>
    <script src="media/js/jquery.dataTables.min.js"></script>
    <script src="media/js/jquery.dataTables.js"></script>

    <link href="media/css/jquery.dataTables.css" rel="stylesheet" />
    <link href="media/css/jquery.dataTables.min.css" rel="stylesheet" />
    <link href="media/css/jquery.dataTables_themeroller.css" rel="stylesheet" />--%>
    
   
    <script type="text/javascript">
        function codeAddress() {
            
            PageMethods.showdata("A", OnSuccess, OnError);
        }

        function OnSuccess(data) {


            if (data.length > 0) {
                setData(data);
            }
        }

        function OnError(error) {
            alert('in error');
        }
        window.onload = codeAddress;


        function setData(data) {
            var doc = $.parseJSON(data);
            alert(doc);
        }
   
        
        
        function DisableRow(tableID)
        {
            try {

                debugger;
                var chkboxlist;
                var lastRow = tableID.rows.length;

                var conf = confirm("Are you sure want to delete ?? ");
                if (conf == true) {
                    for (var i = 1; i < lastRow; i++) {
                        var row = tableID.rows[i];
                        var chkbox = row.cells[0].childNodes[0];
                        var x = $(chkbox).val();
                        if (null != chkbox && true == chkbox.checked) {
                            chkboxlist = chkboxlist + ',' + x;
                            tableID.deleteRow(i);
                            lastRow--;
                            i--;
                        }
                        else if (null != chkbox && false == chkbox.checked) {

                        }
                    }
                }
                else {
                    return false;
                }
                $("#getcheckboxid").val(chkboxlist);
                document.getElementById('<%= getcheckboxid.ClientID %>').value = chkboxlist;
            }
            catch (e) {
                alert(e);
            }
        }

        </script>
    <style type="text/css">
        .modalBackground
        {
            position: absolute;
            z-index: 6000 !important;
            top: 0px;
            left: 0px;
            background-color: #000;
            filter: alpha(opacity=60);
            -moz-opacity: 0.6;
            opacity: 0.6;
        }
    </style> 
   

</head>
<body>
    <form id="form1" runat="server">
         <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
                    <article class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                            <div class="jarviswidget jarviswidget-color-blueDark" id="wid-id-3" data-widget-editbutton="false">
                  <header>
<span class="widget-icon"> <i class="fa fa-table"></i> </span>
<h2>Data table</h2>
</header>
                                 
                                    <div>
                                           <div class="jarviswidget-editbox">
<!-- This area used as dropdown edit box -->
</div>
<!-- widget edit box -->
<div class="jarviswidget-editbox">
<!-- This area used as dropdown edit box -->
</div>
<!-- end widget edit box -->
                   
              <div class="widget-body no-padding">

                   <table id="datatable_tabletools" class="table table-striped table-bordered table-hover">
    <thead>
        <tr>
            <th data-hide="phone">Action</th>
            <th data-hide="phone,tablet">Country</th>
            
        </tr>
    </thead>
   
 
  <tbody id="t1">
<%=getData()%>
 </tbody>
</table>

                                            </div>
  
              <asp:UpdatePanel ID="UpdatePanel_basicProfile"  runat="server">
              <ContentTemplate>
            <table >
         <tr>
                                       <td style="align-content:center">
                                            <input runat="server" type="hidden" id="getcheckboxid" value="0" />
                                       <asp:Button ID="btnadd" CssClass="btn btn-primary" Text="Add"   runat="server"/>
                                                 </td>
                                       <td style="width:90%">
                                            <asp:Button ID="btndisable" CssClass="btn btn-primary" Text="Disable"   runat="server" OnClick="btnAddCountrydisable_Click"  OnClientClick ="return  DisableRow(example);"/>
                                       </td>
                                       <td style="vertical-align:bottom;text-align:start"; >
                                            <div class="row">
                                <div id="divCultureError" runat="server" visible="false"  class="alert alert-success fade in">
<button class="close" data-dismiss="alert">
×
</button>
<i class="fa-fw fa fa-check"></i>
<strong>Success</strong>
</div>
</div> 
</td>

                                           </tr>

            </table>
            <asp:Panel ID="pnlPopup" runat="server" CssClass="smart-form client-form"   BackColor="White" Style="display:none">
           <table style="width:450px;">
                                    
                                    <tr>
                                        <td >
                                            <div class="jarviswidget jarviswidget-color-darken" >
                                                    <header>
                                            <h2 style="color:white; font-size:medium"><span class="widget-icon"> <i class="fa fa-edit"></i> </span>Add Office Location</h2>
            </header></div>

                                        </td>

                                    </tr>
                               <tr><td>
                                            
                                         
                                            <div class="modal-body">
                                                <div class="row">

                        <section class="col col-10">
                                                        <label>Select</label>
                                                        <label class="input">
                                                            
                                                           <asp:DropDownList ID="ddlCountry" DataTextField="name" DataValueField="id" width="100%" runat="server" AppendDataBoundItems="true">
                                                               </asp:DropDownList>
                                                        </label>
                                                    </section>
                                                </div>
                                                <br />

                                            </div>


                                    
                                   
                                        </td>
                                    </tr>

                                </table>
                 
                            <footer>

                                  
                                   <asp:Button ID="btnAddcountryPopUP_MYCountry" runat="server" CssClass="btn btn-primary" OnClick="btnAddcountryPopUP_MYCountry_Click" Text="Add" />
                                   <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click"  CssClass="btn btn-primary" />
                                <br />
                                <br />
                                  
                                </footer>  


        </asp:Panel>
            <asp:ModalPopupExtender ID="mpe" runat="server" TargetControlID="btnadd" PopupControlID="pnlPopup"
            DropShadow="true" BackgroundCssClass="modalBackground" Enabled="True" CancelControlID ="btnCancel" >
        </asp:ModalPopupExtender>

</ContentTemplate>
   </asp:UpdatePanel>
                        </div>
                                   </div>
</article>


    </form>



Step 3 :
C# Code : Put this code in .Cs File  


using System.Data;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System;
using System.Collections.Generic;


namespace Edsetgo
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        DbCon dbcon = new DbCon();
        protected void Page_Load(object sender, EventArgs e)
        {
         
           

        }

       
     
        public string getData()
        {
            string htmlStr = "";
            dbcon.ClearParameters();
            dbcon.AddParameters("@Operation", (int)OperationType.GetOfficeLocation, SqlDbType.SmallInt);
            SqlDataReader dr = dbcon.cmdquery("Ed_GetOfficeLocation_Department_position");
            dbcon.ClearParameters();
            while (dr.Read())
            {
                int id = Convert.ToInt16(dr["id"]);
                string status = dr["status"].ToString();
                string CountryName = dr["CountryName"].ToString();
                if (status == "Enable")
                {
                                htmlStr += "<tr><td><input  type=\"checkbox\"  id=\"chk" + id + "\"   value=\"" + id + "\" onchange=\"myFunction(" + id + ")\" /></td><td>" + CountryName + "</td></tr>";
                }
                else if (status == "Disable")
                {
                               htmlStr += "<tr><td><input  type=\"checkbox\"  id=\"chk" + id + "\" checked value=\"chk" + id + "\"  onchange=\"myFunction()\"/></td><td>" + CountryName + "</td></tr>";

                }
            }

            return htmlStr;
        }
       
        protected void btnAddCountrydisable_Click(object sender, EventArgs e)
        {
            var Checkedid = getcheckboxid.Value;
            string[] checklist = Checkedid.Split(',');
            for (int i = 1; i < checklist.Length; i++)
            {
                try
                {
                    dbcon.AddParameters("@country_Fk", 0, SqlDbType.SmallInt);
                    dbcon.AddParameters("@status", (char)Status.Disable, SqlDbType.Char, 1);
                    dbcon.AddParameters("@Operation", (int)OperationType.DisableOfficeCountry, SqlDbType.SmallInt);
                    dbcon.AddParameters("@id", Convert.ToInt16(checklist[i]), SqlDbType.SmallInt);
                    dbcon.AddParameters("@name", "", SqlDbType.VarChar, 60);
                    dbcon.cmdnonquery("Ed_UpdateOfficeLocation_Department_position");
                    dbcon.ClearParameters();
                    getData();
                }
                catch (Exception ex)
                {
                }
            }

        }
       
     
        protected void btnAddcountryPopUP_MYCountry_Click(object sender, EventArgs e)
        {
            try
            {
                dbcon.AddParameters("@country_Fk", ddlCountry.SelectedValue, SqlDbType.SmallInt);
                SqlDataReader dr = dbcon.cmdquery("Ed_CheckOfficeLocation");
                dbcon.ClearParameters();
                if (dr.Read())
                {
                    if (dr[1].ToString() == "D")
                    {
                        dbcon.AddParameters("@Operation", (int)OperationType.EnableOfficeCountry, SqlDbType.SmallInt);
                        dbcon.AddParameters("@id", 0, SqlDbType.SmallInt);
                        dbcon.AddParameters("@status", (char)Status.Enable, SqlDbType.Char, 1);
                        dbcon.AddParameters("@country_Fk", ddlCountry.SelectedValue, SqlDbType.SmallInt);
                        dbcon.AddParameters("@name", "", SqlDbType.VarChar, 60);
                        dbcon.cmdnonquery("Ed_UpdateOfficeLocation_Department_position");
                        dbcon.ClearParameters();
                    }
                    else
                    {
                       // lblErrorMsg.Visible = true;
                     //   lblErrorMsg.Text = ddlCountry.SelectedItem.Text + " Already added in List";
                        mpe.Show();

                    }
                }
                else
                {
                    dbcon.AddParameters("@country_Fk", ddlCountry.SelectedValue, SqlDbType.SmallInt);
                    dbcon.AddParameters("@status", (char)Status.Enable, SqlDbType.Char, 1);
                    dbcon.AddParameters("@Operation", (int)OperationType.InsertOfficeCountry, SqlDbType.SmallInt);
                    dbcon.AddParameters("@name", "", SqlDbType.VarChar, 60);
                    dbcon.cmdnonquery("Ed_InsertOfficeLocation_Department_position");
                    dbcon.ClearParameters();
                }
             //   log.LogTable("emp_country", Convert.ToInt32(Session["UserIDFk"].ToString()), Convert.ToInt32(Session["UserIDFk"].ToString()));

                getData();

            }
            catch (Exception ex)
            {
              //  exceptionstore.AddEditException(ex, "Admin add/disable country,Department,position screen");

            }

        }
         
   
    }
}