0

How can I align jqGrid column as per the contents loaded in the column. I know jqGrid adjust the column width before loading the data into it, then how can I adjust the width as per the content. Also, the content should not get cut down, goes behind the column.

 jQuery("#jqgrid").jqGrid({
                url: '@Url.Action("GetClassList", "Class")',
                datatype: 'json',
                height: 'auto',
                colNames: ['ClassID','CourseID', '@objLocalizer["Class_Title_GridCol"]','@objLocalizer["ViewCourseDetails"]','@objLocalizer["ViewClassSchedule"]', '@objLocalizer["Class_AssignUser"]','@objLocalizer["ClassCreatedBy"]','@objLocalizer["ClassCreatedDate"]'],
                colModel: [

                    {
                        name: 'Class.ClassID',
                        index: 'Class.ClassID',
                        sortable: true,
                        hidden: true

                    },
                    {
                        name: 'Class.CourseID',
                        index: 'Class.CourseID',
                        sortable: true,
                        hidden: true

                    },
                    {
                        name: 'ClassLang.Title',
                        index: 'ClassLang.Title',
                        sortable: true,
                        formatter: addLink

                    },
                    {
                        name: 'CourseDetails',
                        index: 'CourseDetails',
                        sortable: false,
                        align: 'center',
                        title: false

                    },
                     {
                         name: 'ClassSchedule',
                         index: 'ClassSchedule',
                         sortable: false,
                         align: 'center',
                         title: false

                     },

               {
                   name: 'AssignUser',
                   index: 'AssignUser',
                   formatter:'date',
                   sortable: false,
                   align: 'center',
                   title: false


               },

               {
                   name: 'UserName',
                   index: 'UserName',

                   sortable: true
               },
               {
                   name: 'Class.WhenCreated',
                   index: 'Class.WhenCreated',

                   formatter:'date',
                   sortable: true
               }],

                rowNum: 10,
                rowList: [10, 20, 30],
                pager: '#pjqgrid',
                sortname: 'id',
                toolbarfilter: true,
                viewrecords: true,
                sortorder: "asc",
                loadonce: true,
                ignoreCase: true,
                gridComplete: function () {
                    var myGrid = $("#jqgrid");

                    //$(this).jqGrid('hideCol', 'cb'); // code is commented for grid size get reduce  (Default checkboxes hidden)
                    var ids = jQuery("#jqgrid").jqGrid('getDataIDs');

                    for (var i = 0; i < ids.length; i++) {
                        var cl = ids[i];
                        var classSchedule='Class Schedule';

                        Au = "<button class='btn btn-xs btn-default' data-placement='center' title='@objLocalizer["Class_AssignUser"]' onclick='AssignUser(" + cl + ")'\"><i class='fa fa-users fa-lg' aria-hidden='true'></i></button>";
                        Cd="<button class='btn btn-xs btn-default' data-placement='center' title='@objLocalizer["ViewCourseDetails"]' onclick='CourseDetails(" + cl + ")'\"><i class='fa fa-file fa-lg' aria-hidden='true'></i></button>";
                        Cs="<button class='btn btn-xs btn-default' data-placement='center' title='@objLocalizer["ViewClassSchedule"]' onclick='ViewClassSchedule(" + cl + ")'\"><i class='fa fa-calendar fa-lg' aria-hidden='true'></i></button>";

                        jQuery("#jqgrid").jqGrid('setRowData', ids[i], {
                            AssignUser: Au,
                            CourseDetails:Cd,
                            ClassSchedule:Cs
                        });
                    }
                    $("#progbar").css('width', '100%')
                    $("#progess").hide();
                    $("#grid").css("visibility", 'visible');

                },
                editurl: " ",
                caption: "",
                multiselect: false,
                autowidth: true,


            });
            jQuery("#jqgrid").jqGrid('navGrid', "#pjqgrid", {
                edit: false,
                add: false,
                del: true
            });



            jQuery("#jqgrid").jqGrid('navButtonAdd', '#pjqgrid_left', { // "#list_toppager_left"
                caption: "",
                title: '@objLocalizer["Class_AddClass_Btn"]',
                buttonicon: 'ui-icon-plus',
                onClickButton: function () {
                    sessionStorage.removeItem('Showkey');
                    document.location.href = '@Url.Action("AddClass", "Class")';
                    //'/Account/Adduser';
                }
            });
            ////
            jQuery("#m1").click(function () {
                var s;
                s = jQuery("#jqgrid").jqGrid('getGridParam', 'selarrrow');

            });
            jQuery("#m1s").click(function () {
                jQuery("#jqgrid").jqGrid('setSelection', "13");
            });
            // remove classes
            $(".ui-jqgrid").removeClass("ui-widget ui-widget-content");
            $(".ui-jqgrid-view").children().removeClass("ui-widget-header ui-state-default");
            $(".ui-jqgrid-labels, .ui-search-toolbar").children().removeClass("ui-state-default ui-th-column ui-th-ltr");
            $(".ui-jqgrid-pager").removeClass("ui-state-default");
            $(".ui-jqgrid").removeClass("ui-widget-content");

            // add classes
            $(".ui-jqgrid-htable").addClass("table table-bordered table-hover");
            $(".ui-jqgrid-btable").addClass("table table-bordered table-striped");

            $(".ui-pg-div").removeClass().addClass("btn btn-sm btn-primary");
            $(".ui-icon.ui-icon-plus").removeClass().addClass("fa fa-plus");
            $(".ui-icon.ui-icon-pencil").removeClass().addClass("fa fa-pencil");
            $(".ui-icon.ui-icon-trash").removeClass().addClass("fa fa-trash-o");
            $(".ui-icon.ui-icon-search").removeClass().addClass("fa fa-search");
            $(".ui-icon.ui-icon-refresh").removeClass().addClass("fa fa-refresh");
            $(".ui-icon.ui-icon-disk").removeClass().addClass("fa fa-save").parent(".btn-primary").removeClass("btn-primary").addClass("btn-success");
            $(".ui-icon.ui-icon-cancel").removeClass().addClass("fa fa-times").parent(".btn-primary").removeClass("btn-primary").addClass("btn-danger");

            $(".ui-icon.ui-icon-seek-prev").wrap("<div class='btn btn-sm btn-default'></div>");
            $(".ui-icon.ui-icon-seek-prev").removeClass().addClass("fa fa-backward");

            $(".ui-icon.ui-icon-seek-first").wrap("<div class='btn btn-sm btn-default'></div>");
            $(".ui-icon.ui-icon-seek-first").removeClass().addClass("fa fa-fast-backward");

            $(".ui-icon.ui-icon-seek-next").wrap("<div class='btn btn-sm btn-default'></div>");
            $(".ui-icon.ui-icon-seek-next").removeClass().addClass("fa fa-forward");

            $(".ui-icon.ui-icon-seek-end").wrap("<div class='btn btn-sm btn-default'></div>");
            $(".ui-icon.ui-icon-seek-end").removeClass().addClass("fa fa-fast-forward");

            var bottomPagerDiv = $("div#pjqgrid")[0];
            //$("#refresh_jqgrid", bottomPagerDiv).remove();
            $("#jqgrid_ilcancel", bottomPagerDiv).remove();
            $("#jqgrid_ilsave", bottomPagerDiv).remove();
            $("#del_jqgrid", bottomPagerDiv).remove();
            $("#jqgrid_iledit", bottomPagerDiv).remove();
            $("#jqgrid_ilsave", bottomPagerDiv).remove();
            $("#Enroll_btn").find('span').remove();

            $('#refresh_jqgrid').attr('title', '@objLocalizer["Class_Refresh_Btn"]');
            $('#search_jqgrid').attr('title', '@objLocalizer["Class_Search_Btn"]');


            $(window).on('resize.jqGrid', function () {
                $("#jqgrid").jqGrid('setGridWidth', $("#content").width());
            })

In some columns I have used icons also, but column looks bigger as compared to column. Below is the screenshot Grid Any help on this appreciated !

JSON Response

[{
    "Class": {
        "ClassID": 2,
        "CourseID": 2,
        "ClassStatusID": 1,
        "ClassTypeID": 1,
        "InstructorID": null,
        "AlternateInstructorID": null,
        "ContactPersonID": null,
        "CurrencyID": 2,
        "CertificateID": null,
        "AllowSelfEnrollment": true,
        "ClassSizeMin": 150,
        "ClassSizeMax": 170,
        "Username": "test",
        "ClassUrl": "www.google.com",
        "StartDate": "2016-10-23T00:00:00",
        "EndDate": "2016-10-23T00:00:00",
        "DiscountedCoursePrice": 180.00,
        "CoursePrice": 210.00,
        "Password": null,
        "WhoCreated": 3,
        "WhenCreated": "2017-01-02T15:30:45.623",
        "WhoModified": 3,
        "WhenModified": "2017-01-03T01:00:45.623",
        "PasswordString": null,
        "CoursePriceString": null,
        "DiscountedCoursePriceString": null
    },
    "ClassLang": {
        "ClassLangID": 5,
        "ClassID": 2,
        "LanguageTypeID": 3,
        "Title": "de-DE_Introduction to Piano",
        "Description": "de-DE_Introduction to Piano",
        "WhoCreated": null,
        "WhenCreated": null,
        "WhoModified": null,
        "WhenModified": null
    },
    "UserName": "User admin"
}, {
    "Class": {
        "ClassID": 3,
        "CourseID": 3,
        "ClassStatusID": 2,
        "ClassTypeID": 1,
        "InstructorID": null,
        "AlternateInstructorID": null,
        "ContactPersonID": null,
        "CurrencyID": 2,
        "CertificateID": null,
        "AllowSelfEnrollment": true,
        "ClassSizeMin": 140,
        "ClassSizeMax": 180,
        "Username": "test",
        "ClassUrl": "www.google.com",
        "StartDate": "2016-10-23T00:00:00",
        "EndDate": "2016-10-23T00:00:00",
        "DiscountedCoursePrice": 180.00,
        "CoursePrice": 210.00,
        "Password": null,
        "WhoCreated": 3,
        "WhenCreated": "2017-01-02T15:30:45.623",
        "WhoModified": 3,
        "WhenModified": "2017-01-03T01:00:45.623",
        "PasswordString": null,
        "CoursePriceString": null,
        "DiscountedCoursePriceString": null
    },
    "ClassLang": {
        "ClassLangID": 8,
        "ClassID": 3,
        "LanguageTypeID": 3,
        "Title": "de-DE_Class Learn classical music",
        "Description": "de-DE_Class Learn classical music",
        "WhoCreated": null,
        "WhenCreated": null,
        "WhoModified": null,
        "WhenModified": null
    },
    "UserName": "User admin"
}, {
    "Class": {
        "ClassID": 4,
        "CourseID": 4,
        "ClassStatusID": 2,
        "ClassTypeID": 1,
        "InstructorID": null,
        "AlternateInstructorID": null,
        "ContactPersonID": null,
        "CurrencyID": 2,
        "CertificateID": null,
        "AllowSelfEnrollment": true,
        "ClassSizeMin": 15,
        "ClassSizeMax": 17,
        "Username": "test",
        "ClassUrl": "www.google.com",
        "StartDate": "2016-10-23T00:00:00",
        "EndDate": "2016-10-23T00:00:00",
        "DiscountedCoursePrice": 180.00,
        "CoursePrice": 210.00,
        "Password": null,
        "WhoCreated": 3,
        "WhenCreated": "2017-01-02T15:30:45.623",
        "WhoModified": 3,
        "WhenModified": "2017-01-03T01:00:45.623",
        "PasswordString": null,
        "CoursePriceString": null,
        "DiscountedCoursePriceString": null
    },
    "ClassLang": {
        "ClassLangID": 11,
        "ClassID": 4,
        "LanguageTypeID": 3,
        "Title": "de-DE_Playing Electric blue guitar",
        "Description": "de-DE_Playing Electric blue guitar",
        "WhoCreated": null,
        "WhenCreated": null,
        "WhoModified": null,
        "WhenModified": null
    },
    "UserName": "User admin"
}]
XamDev
  • 3,377
  • 12
  • 58
  • 97
  • 1
    Please include in every your question the version of jqGrid, which you use, and the fork. The solution for [free jqGrid](https://github.com/free-jqgrid/jqGrid) fork (starting with the first 4.8 version) is easy, but the solution for other versions/forks could be very complex. Moreover, you use names, which contains dots (like `name: 'Class.ClassID'`). It could be origin of other problems especially in old versions of jqGrid. It's better to use `jsonmap` instead. The usage of `setRowData` in the loop inside of `gridComplete` makes the grid **much more slowly**. It's good to replace it. – Oleg Jan 13 '17 at 15:37
  • I am using 4.5.3 version. I know the version is old, but we are at release stage so cannot change version immediately. So it will be helpful if you provide the solution with provided version. – XamDev Jan 13 '17 at 15:42

1 Answers1

1

You can try to use autoWidthColumns method which I published here for many years. I described it in the old answer and in this one. I should warn you that autoWidthColumns method works very slowly especially for large grids.

I would strictly recommend you to upgrade to the current version (4.13.6) of free jqGrid 4.13.6, which contains the functionality, which you require. It is described in the wiki article. What you should do in free jqGrid is just placement of autoResizable: true in every column, which width you want be able to "autoresize" based on the content of the column. By adding the property autoresizeOnLoad: true you will have the required width of the grid.

It's important to understand that the version 4.5.3 is dead since a long time. It's not supported of cause. Instead of investing your time to create a Frankenstein (or a zombie) from cadaver, you should just use the version of jqGrid, which is alive. As additional benefit you can reduce the code of your program in many times and the program will have much better performance.

By the way the current code of gridComplete is anti pattern, because calling of setRowData in the loop is the worst way to create custom content in the column. Changing of one element on the page follow web browser reflow of all existing element on the page. You should replace gridComplete to at least custom formatter in the columns AssignUser, CourseDetails and ClassSchedule (in the same way likke you do already in ClassLang.Title column). It will improve performance on the grid in multiple times. You should of cause add gridview: true option in all your jqGrids (free jqGrid set gridview: true by default). See the old answer for more details.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • @Olegs just small doubt, is there any difference between free jqGrid and trirand.com jqGrid ? – XamDev Jan 13 '17 at 16:27
  • @Rohit: "jqGrid" not exists since end of 2014. Tony Tomov, the main developer of old jqGrid changed the license agreement at the middle of December 2014 (see [the post](http://www.trirand.com/blog/?p=1438)) in jqGrid 4.7.1 and made the product not more free. You can see the current prices [here](http://guriddo.net/?page_id=103334). Thus, I started the development of free jqGrid at the end of 2014 to provide it for free (under the same MIT/GPL license) the people, who used jqGrid 4.7 and early version before. I tried to hold maximal compatibility with old versions and thus use 4.x.y versions. – Oleg Jan 13 '17 at 16:34
  • @Rohit: In other words: there are no more jqGrid. There are exist two forks, both based on jqGrid 4.7: 1) **commertial** Guriddo jqGrid JS, which current version is 5.2.0 and 2) free jqGrid, with the current version 4.13.6, which I develop and provide for free. "free jqGrid" and "Guriddo jqGrid" are the names of the produces. – Oleg Jan 13 '17 at 16:38
  • thanks for the vital information. Will try the lastest version of free jgGrid in some days. Very helpful ! – XamDev Jan 13 '17 at 16:47
  • @Rohit: You are welcome! You can include an example of JSON response from `@Url.Action("GetClassList", "Class")` and I could gives you some advices how to reduce your code. It's important to know which property of every item is unique (which can be used as native rowid). Do you inserted `id` property in every item? I'd recommend you additionally to consider to use `loadonce: true` scenario because you have relatively small set of items (<1000 rows). – Oleg Jan 13 '17 at 17:12
  • Sorry for the delayed reply. I have added the JSON response as you have asked ! I have updated the version now. Still I am facing the same issue. It will be helpful if you guide on this ! – XamDev Feb 13 '17 at 09:17