Skip to main content

How to bind data in jqgrid in Asp.net(C#)


Here I will explain how to bind data in jqgrid. First of all create a Table for save the data and then after stored procedure for retrive data from table.
 

CREATE TABLE [dbo].[Student](
	[StudentID] [int] IDENTITY(1,1) NOT NULL,
	[FirstName] [nvarchar](50) NULL,
	[LastName] [nvarchar](50) NULL,
	[Standard] [int] NULL,
	[Division] [nvarchar](5) NULL,
	[Address] [nvarchar](500) NULL,
	[Mobileno] [varchar](20) NULL,
 CONSTRAINT [PK__Student__32C52A795B736AEC] PRIMARY KEY CLUSTERED 
(
	[StudentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]




CREATE PROCEDURE [dbo].[WB_Fill_StudentInfo] 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

  SELECT * FROM Student ORDER BY StudentID
END 

In this code snippest i will set cell color conditionally, Open fancybox popup, Display Image and also add checkbox selection.
 


Default.aspx


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>jQ Grid In ASP.NET C#</title>
    <link rel="stylesheet" href="code/jqGrid-4.5.2/css/ui.jqgrid.css" type="text/css" />
    <link rel="stylesheet" href="code/fancybox/source/jquery.fancybox.css" type="text/css" media="screen" />
    <link type="text/css" href="css/jquery-ui-1.9.2.custom.css" rel="stylesheet" />
    <link type="text/css" href="css/ui.jqgrid.css" rel="stylesheet" />
    <script type="text/javascript" src="Script/jquery-1.8.3.js"></script>
    <script type="text/javascript" src="Script/jquery-ui-1.9.2.custom.js"></script>
    <script src="Script/grid.locale-en.js" type="text/javascript"></script>
    <script src="Script/jquery.jqGrid.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="fancybox/source/jquery.fancybox.pack.js"></script>

    <style type="text/css">
        .my-highlight {
            background-color: green;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            var width = $(window).width() - 50; // for get window width and set grid width
            var height = $(window).height() - 100;//for get window height and set grid height
            var grid = $("#dataGrid");
            $("#dataGrid").jqGrid({
                url: 'Default.aspx/GetDataFromDB',
                datatype: 'json',
                mtype: 'POST',
                serializeGridData: function (postData) {
                    return JSON.stringify(postData);
                },
                ajaxGridOptions: { contentType: "application/json" },
                loadonce: true,
                width: 900,
                height: 500,
                search: true,
                autowidth: false,
                shrinkToFit: true,
                colNames: ['Select', 'Profile', 'Student ID', 'First Name', 'Last Name', 'Standard', 'Division', 'Address', 'Mobileno'],
                colModel: [
                     { name: 'StudentID', width: 50, id: 'StudentID', index: 'StudentID', editable: true, edittype: 'checkbox', editoptions: { value: "True:False", defaultValue: "False" }, formatoptions: { disabled: false } },
                     {
                         name: 'StudentID',
                         width: 50,
                         fixed: true,
                         formatter: function () {
                             return "<img src='Images/profile.png' alt='my image' />";
                         }
                     },
                      { name: 'StudentID', index: 'Student ID', width: 80 },  
                     { name: 'FirstName', index: 'FirstName', width: 100, align: 'center', editable: false, sortable: false, formatter: fancyBoxFormatter },
                      { name: 'LastName', index: 'LastName', width: 100, align: 'center', editable: false, sortable: false, formatter: fancyBoxFormatter },                      
                                {
                                    name: 'Standard', index: 'Standard', width: 90, formatter: function (cellvalue, options, rowObject) {
                                        if (cellvalue == '12')
                                            return '<span style="background-color: red; ">' + cellvalue + '</span>';

                                        else if (cellvalue == '10')
                                            return '<span style="background-color: green; ">' + cellvalue + '</span>';

                                        else
                                            return cellvalue;
                                    }
                                },
                                { name: 'Division', index: 'Division', width: 90 },
                                    { name: 'Address', index: 'Address', width: 150 },
                                { name: 'Mobileno', index: 'Mobileno', width: 100 }

                ],
                viewrecords: true,
                gridview: true,
                rowNum: 100000,
                sortable: true,
                sortorder: "asc",
                loadComplete: function () {
                    $(".fancybox").fancybox();
                },
                jsonReader: {
                    root: function (obj) {
                        return obj.d;
                    },
                    repeatitems: false
                },
                caption: 'Nikhil Sangani'
            });
        });

        function fancyBoxFormatter(cellvalue, options, rowObject) {
            var result,
                link,
                fancyBoxHTML,
                fancyBoxContent;
            link = "<a class=\"fancybox\" href=\"#data" + options.rowId + "\">" + cellvalue + "</a>";          
            fancyBoxHTML = "<div style=\"display:none\"><div id=\"data" + options.rowId + "\">" + cellvalue + "</div></div>";
            return link + fancyBoxHTML;
        }
    </script>
</head>
<body style="font-family: Arial; font-size: 10pt">
    <form runat="server" id="form1">
        <asp:HiddenField runat="server" ID="hdnlist" ClientIDMode="Static" />
        <table id="dataGrid" style="text-align: center;"></table>
    </form>
</body>
</html>


Default.aspx.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace jQGridExample
{
    public partial class Default : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static List<Dictionary<string, object>> GetDataFromDB()
        {
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection(@"Data Source=(local); Initial Catalog=emp; Uid=sa; pwd=sw;"))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    con.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "WB_Fill_StudentInfo";
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dt);
                    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                    Dictionary<string, object> row;
                    foreach (DataRow dr in dt.Rows)
                    {
                        row = new Dictionary<string, object>();
                        foreach (DataColumn col in dt.Columns)
                        {
                            row.Add(col.ColumnName, dr[col]);
                        }
                        rows.Add(row);
                    }
                    return rows;
                }
            }
        }
    }
}


When the json data length is increse then it gives error so here I will set maxJsonLength in webconfig.

<configuration>
<system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="50000000"/>
      </webServices>
    </scripting>
  </system.web.extensions>
</configuration>

Comments

Popular posts from this blog

How To See Logs Of Dropped Tables From The Database in MS SQL.

Here, I will explain you how you can see logs of users. Step 1 : First, create a new database with name "test". Step 2 : Create a new table. Step 3 : Now, go and drop the table by running the following command. Step 4 : Now, select your database under Object Explorer and go to Reports >> Standard Reports >> Schema Changes History. Step 5 : You will then see the schema change history. The report will show you who has dropped this table. Finally, you can locate the user activity with the help of log.

How To Deploy .net Core Application On Linux

Here, I can explain steps to deploy .net core application on linux machine. Step 1 - Publish your .net Core application: First, create a .net core application on VS; you can make an MVC project or Web API project and if you already have an existing project, then open it. Right Click on your project Click on publish Now create a new publish profile, and browse the folder where you want to publish your project dll Click on publish so it will create your dll in the folder Step 2 - Install required .net Module on Linux: Now we have our web application dll and now we need to host it on the Linux environment. First, we need to understand how the deployment works in Linux. .Net applications run on Kestrel servers and we run Apache or Nginx server in Linux environments, which acts as a proxy server and handles the traffic from outside the machine and redirects it to the Kestrel server so we will have Apache or Nginx server as the middle layer. In this article, we will use Apache as a proxy ser

List Of Commonly Used Angular Commands

1) To get the npm version,    npm -v 2) To get the node version,    node -v 3) To get the Angular version,    ng v  4) To get the Jasmine version,    jasmine -v  5) To get the Karma version,    karma --version  6) To install Angular CLI,    npm install @angular/cli -g   npm install @angular/cli 7) To install the next version of Angular CLI, v   npm install @angular/cli@next  8) To get help in the terminal,    ng help 9) To create a new project in Angular,    ng new project-name  10) To skip external dependencies while creating a new project,    ng new project-name --skip-install  11) To run the Angular project,   ng serve (or) npm start (or) ng serve --force  12) Dry Run,   ng new project-name --dry-run 13) To create a new component in the Angular Project,   ng generate component component-