Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

jqGrid and ASP.Net Web Forms

0.00/5 (No votes)
12 Apr 2012 1  
I have been getting the hang of using jqGrid from with asp.net web forms.  So I will to  brief walkthru.first add the following HTML to your

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

I have been getting the hang of using jqGrid from with asp.net web forms.  So I will to  brief walkthru.

first add the following HTML to your page:

<table id="list4"></table>
<div id="gridpager"></div>

Now in your docready function or a function you plan to load the grid in add the following code:

$("#list4").jqGrid({
datatype: "local",
height: 250,
loadtext: "Loading...",
colNames: ['Col1', 'Col2', 'Col3'],
colModel: [
     { name: 'Col1', index: 'Col1', hidden: true },
     { name: 'Col2', index: 'Col2', sorttype: "text" },
     { name: 'Col3', index: 'Col3', width: 100, sorttype: "text"  }
   ],
multiselect: false,
pager: '#gridpager',
pgbuttons: false,
pgtext: null,
recordtext: '',
viewrecords: true,
autowidth: true,
caption: "Summary"
});
$("#list4").navGrid('#gridpager',
{view:false,edit:false,search:true,add:false,del:false,refresh:false}
);

var dArray = "{";
dArray += "'userid': '" + <%=Page.User.Identity.Name %> + "',";
dArray += "'fromdate': '" + $("#<%= txtFrom.ClientID %>").val() + "',";
dArray += "'todate': '" + $("#<%= txtTo.ClientID %>").val() + "'";
dArray += "}";

$.ajax({
type: "POST",
url: "default.aspx/GetGridData",
data: dArray,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (response) {
    //$("#list4").clearGridData();
    var gd = eval('(' + response.d + ')');
    for (row in gd){
 $("#list4").jqGrid('addRowData', row, gd[row]);
    }
},
error: function (response) {
    alert(response.responseText);
}
});

Now I would say to use a web service but Ihave certain pages where this is just a one of so I amusing PageMethods here.  Create your Pagemethod to return the data as a JSON string.  i will also provide a helper utility to convert a dataTable to a JSON string.

'pagemethod
 <WebMethod()> _
    Public Shared Function GetGridData(userid As String, fromdate As String, todate As String) As String
        Dim result As String = String.Empty
        Try
            Dim params As New List(Of SqlParameter)
            params.Add(New SqlParameter("userid", userid))
            params.Add(New SqlParameter("from", String.Format("{0} 12:00 AM", fromdate)))
            params.Add(New SqlParameter("to", String.Format("{0} 11:59 PM", todate)))
            Using dt As DataTable = SqlHelper.GetDataTable("stp_getSomeGridDataProcedure", CommandType.StoredProcedure, params.ToArray)
                result = ConvertDataTableToJSON(dt)
            End Using

        Catch ex As Exception

        End Try

        Return result
    End Function
   

and the helper function:

'utility function to convert datatable to json
Public Shared Function ConvertDataTableToJSON(Dt As DataTable) As String

        Dim StrDc As String() = New String(Dt.Columns.Count) {}
        Dim HeadStr As String = String.Empty
        Dim hdrLst As New List(Of String)
        For i As Integer = 0 To Dt.Columns.Count - 1
            StrDc(i) = Dt.Columns(i).Caption
            hdrLst.Add("""" + StrDc(i) + """ : """ + StrDc(i) + i.ToString() + "¾" + """")
        Next
        HeadStr = Join(hdrLst.ToArray, ",")
        Dim Sb As New StringBuilder()
        Sb.Append("{""" + Dt.TableName + """ : [")
        For i As Integer = 0 To Dt.Rows.Count - 1
            Dim TempStr As String = HeadStr
            Sb.Append("{")
            For j As Integer = 0 To Dt.Columns.Count - 1
                Dim replaceString As String = Dt.Columns(j).ToString & j.ToString() & "¾"
                Dim newString As String = Dt.Rows(i)(j).ToString()
                TempStr = TempStr.Replace(replaceString, newString)
            Next
            Sb.Append(TempStr + "},")
        Next

        Sb = New StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1))
        Sb.Append("]}")

        Return Sb.ToString()
    End Function

Remember to update the column names and the sql to reflect your data.  Hope this helps someone else.  Oh, this is using the datatype="local", you could easily move the ajax call into the datatype as a fucntion as such:

datatype: function (pdata) {
 var dArray = "{";
 dArray += "'userid': '" + <%=Page.User.Identity.Name %> + "',";
 dArray += "'fromdate': '" + $("#<%= txtFrom.ClientID %>").val() + "',";
 dArray += "'todate': '" + $("#<%= txtTo.ClientID %>").val() + "'";
 dArray += "}";

 $.ajax({
  type: "POST",
  url: "default.aspx/GetGridData",
  data: dArray,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  async: true,
  success: function (response) {
   //$("#list4").clearGridData();
   var gd = eval('(' + response.d + ')');
   for (row in gd){
    $("#list4").jqGrid('addRowData', row, gd[row]);
   }
  },
  error: function (response) {
   alert(response.responseText);
  }
 });
},

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here