Click here to Skip to main content
15,890,690 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi developers,

I tried and implemented jqGrid. After that ineeds to add edit and delete button on each row. I tried to some code its not working for me( my custom edit and delete buttons on each jqGrid row) and how i can i pass my row details to specific ".ashx" page.


The code i tried is,

<title></title>
    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.11/themes/redmond/jquery-ui.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script src="js/i18n/grid.locale-en.js"type="text/javascript"></script>
    <script src="js/jquery.tablednd.js" type="text/javascript"></script>
    <script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            var last_row = -1;
            $("#UsersGrid").jqGrid({
                url: 'jqGridHandler.ashx',
                datatype: 'json',
                height: 250,
                colNames: ['UserID', 'UserName', 'FirstName', 'MiddleName', 'LastName', 'EmailID', 'custom'],
                colModel: [
                        { name: 'UserID', index: 'UserID', width: 100, sortable: true },
                        { name: 'UserName', width: 100, sortable: false, editable: true },
                        { name: 'FirstName', width: 100, sortable: false },
                        { name: 'MiddleName', width: 100, sortable: false, editable: true, edittype: "textarea", editoptions: { rows: "2", cols: "37"} },
                        { name: 'LastName', width: 100, sortable: false },
                        { name: 'EmailID', width: 150, sortable: false },
                        { label: 'My Custom Column1', name: 'custom', index: 'custom', width: 120 }
                    ],
                loadComplete: function () {
                    var grid = $("#UsersGrid");
                    var getColumnIndexByName = function (grid, columnName) {
                        var cm = grid.jqGrid('getGridParam', 'colModel'), i = 0, l = cm.length;
                        for (; i < l; i += 1) {
                            if (cm[i].name === columnName) {
                                return i;
                            }
                        }
                        return -1;
                    }
                    var iCol = getColumnIndexByName(grid, 'custom'); // 'custom' - name of the actions column
                    grid.children("tbody")
                .children("tr.jqgrow")
                .children("td:nth-child(" + (iCol + 1) + ")")
                .each(function () {
                    $("<div>",
                        {
                            title: "edit",
                            click: // how can i edit and pass row details to a "EditUserDetails.ashx" page</p>
                            mouseover: function () {
                                $(this).addClass('ui-state-hover');
                            },
                            mouseout: function () {
                                $(this).removeClass('ui-state-hover');
                               
                            }
                        }).css({ "margin-left": "5px", float: "left" })
                       .addClass("ui-pg-div ui-inline-save")
                       .attr('id', "UserID")
                       .append('<span class="ui-button-icon-primary ui-icon ui-icon-disk"></span>')
                       .appendTo($(this).children("div"));
                    $("<div>",
                            {
                                title: "delete",
                        click: // how can i pass rowid a "deleteUser.ashx" page
                                mouseover: function () {
                                    $(this).addClass('ui-state-hover');
                                },
                                mouseout: function () {
                                    $(this).removeClass('ui-state-hover');
                                }

                            }).css({ "margin-left": "5px", float: "left" })
                           .addClass("ui-pg-div ui-inline-custom")
                           .attr('id', "UserID")
                           .append('<span class="ui-button-icon-primary ui-icon ui-icon-circle-check"></span>')
                           .appendTo($(this).children("div"));
                });
                },
                rowNum: 10,
                rowList: [10, 20, 30],
                pager: '#UsersGridPager',
                sortname: 'UserID',
                viewrecords: true,
                sortorder: 'asc',
                caption: 'JSON Example',
                deleteurl: 'deleteColumn.ashx'
            });
            $("#UsersGrid").jqGrid('navGrid', '#UsersGridPager', { edit: false, add: false, del: false }).navButtonAdd('#UsersGridPager', {
                caption: "Add",
                buttonicon: "ui-icon-add",
                onClickButton: function () {
                    alert("Adding Row");
                },
                position: "last"
            });
            $(".sendbuttons").click(function () {
                alert("got to 1");
            });
        });
    </script>
</head>
<body>
    <table id="UsersGrid" ></table>
    <div id="UsersGridPager"></div>
</body>
</html>


the code i used to display the grid details is(jqGridHandler.ashx.cs page):

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

namespace jqGridInWebForm
{
    public struct JQGridResults
    {
        public int page;
        public int total;
        public int records;
        public JQGridRow[] rows;
    }
    public struct JQGridRow
    {
        public int id;
        public string[] cell;
    }
    [Serializable]
    public class User
    {
        public int UserID { get; set; }
        public string UserName { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public string EmailID { get; set; }
    }
    public class jqGridHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;
            string _search = request["_search"];
            string numberOfRows = request["rows"];
            string pageIndex = request["page"];
            string sortColumnName = request["sidx"];
            string sortOrderBy = request["sord"];
            int totalRecords;
            Collection<User> users = GetUsers(numberOfRows, pageIndex, sortColumnName, sortOrderBy, out totalRecords);
            string output = BuildJQGridResults(users, Convert.ToInt32(numberOfRows), Convert.ToInt32(pageIndex), Convert.ToInt32(totalRecords), sortOrderBy);
            response.Write(output);
        }
        private string BuildJQGridResults(Collection<User> users, int numberOfRows, int pageIndex, int totalRecords, string sortOrderBy)
        {
            JQGridResults result = new JQGridResults();
            List<JQGridRow> rows = new List<JQGridRow>();
            int pageStartIndex=1;
            if (pageIndex != 1)
            {
              pageStartIndex = ((pageIndex * numberOfRows) - (numberOfRows)) + 1;
            }
            for (int k = pageStartIndex - 1; k < totalRecords; k++)
            {
                JQGridRow row = new JQGridRow();
                row.id = users[k].UserID;
                row.cell = new string[6];
                row.cell[0] = users[k].UserID.ToString();
                row.cell[1] = users[k].UserName;
                row.cell[2] = users[k].FirstName;
                row.cell[3] = users[k].MiddleName;
                row.cell[4] = users[k].LastName;
                row.cell[5] = users[k].EmailID;
                rows.Add(row);
            }
            result.rows = rows.ToArray();
            result.page = pageIndex;
            result.total = (totalRecords + numberOfRows - 1) / numberOfRows;
            result.records = totalRecords;
            return new JavaScriptSerializer().Serialize(result);
        }
        private Collection<User> GetUsers(string numberOfRows, string pageIndex, string sortColumnName, string sortOrderBy, out int totalRecords)
        {
            Collection<User> users = new Collection<User>();
            string connectionString = "Data Source=HYD-NPULIVARTHY;Initial Catalog=test2;Integrated Security=True";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand command = new SqlCommand())
                {
                    command.Connection = connection;
                    string sqlCommand = "select * from userDetails";
                    if (sortOrderBy == "desc")
                        sqlCommand = "select * from userDetails ORDER BY UserID DESC";
                    command.CommandText = sqlCommand;
                    command.CommandType = CommandType.Text; // StoredProcedure;

                    SqlParameter paramPageIndex = new SqlParameter("@PageIndex", SqlDbType.Int);
                    paramPageIndex.Value = Convert.ToInt32(pageIndex);
                    command.Parameters.Add(paramPageIndex);

                    SqlParameter paramColumnName = new SqlParameter("@SortColumnName", SqlDbType.VarChar, 50);
                    paramColumnName.Value = sortColumnName;
                    command.Parameters.Add(paramColumnName);

                    SqlParameter paramSortorderBy = new SqlParameter("@SortOrderBy", SqlDbType.VarChar, 4);
                    paramSortorderBy.Value = sortOrderBy;
                    command.Parameters.Add(paramSortorderBy);

                    SqlParameter paramNumberOfRows = new SqlParameter("@NumberOfRows", SqlDbType.Int);
                    paramNumberOfRows.Value = Convert.ToInt32(numberOfRows);
                    command.Parameters.Add(paramNumberOfRows);

                    SqlParameter paramTotalRecords = new SqlParameter("@TotalRecords", SqlDbType.Int);
                    totalRecords = 0;
                    paramTotalRecords.Value = totalRecords;
                    paramTotalRecords.Direction = ParameterDirection.Output;
                    command.Parameters.Add(paramTotalRecords);
                    connection.Open();
                    using (SqlDataReader dataReader = command.ExecuteReader())
                    {
                        User user;
                        while (dataReader.Read())
                        {
                            user = new User();
                            user.UserID = (int)dataReader["UserID"];
                            user.UserName = Convert.ToString(dataReader["UserName"]);
                            user.FirstName = Convert.ToString(dataReader["FirstName"]);
                            user.MiddleName = Convert.ToString(dataReader["MiddleName"]);
                            user.LastName = Convert.ToString(dataReader["LastName"]);
                            user.EmailID = Convert.ToString(dataReader["EmailID"]);
                            users.Add(user);
                        }
                    }
                    totalRecords = users.Count;
                }
                return users;
            }
        }
        public bool IsReusable
        {
            // To enable pooling, return true here.
            // This keeps the handler in memory.
            get { return false; }
        }
    }   
}
Posted
Updated 4-Sep-13 2:07am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900