Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

DataGrid & Paging using Ajax

3.29/5 (3 votes)
25 Oct 2007CPOL1 min read 1   186  
Achieving the DataGrid functionality with paging using User control and Ajax

Introduction

The DataGrid is displayed without a single line of code in the Code Behind Page. The whole functionality depends on Ajax and client side coding. No doubt we have a user control which is used to bind the data.

Using the Code

RenderView is a static function in the VuMgr Class. RenderView returns the HTML string of user control after data bind. the method creates a page object, and gets a reference to a user control object after loading that in the page, and binds the user control with the Reflection method. It then adds the control in the page and gets the HTML string by executing the page dynamically. This method is a idea from scottgu's official webblog site.

C#
public static string RenderView(string path,object data)
{
    Page dynamicPage = new Page();
    UserControl uc = (UserControl)dynamicPage.LoadControl(path);
    Type t = uc.GetType();
    FieldInfo f = t.GetField("data");
    f.SetValue(uc,data);
    dynamicPage.Controls.Add(uc);

    StringWriter output = new StringWriter();
    HttpContext.Current.Server.Execute(dynamicPage,output,false);

    return output.ToString();
}

This page load handler is written in the user control, and a public variable data is declared to bind the user control using Reflection method:

C#
protected void Page_Load(object sender, EventArgs e)
{
    uc.DataSource=data;
    uc.DataBind();
}

WebMethod is used to call from the client side using Ajax, this takes the page number as Parameter:

C#
[WebMethod]
public string GetEmpDataTable(string pageno)
{
    string str = "server=ServerName;
			Database=AdventureWorks;Trusted_Connection=True;";
    SqlCommand cmd = new SqlCommand("GETEMPDETAILS",new SqlConnection(str));
    cmd.CommandType=CommandType.StoredProcedure;
    cmd.Parameters.Add("@pageno",pageno);
    cmd.Parameters.Add("@pagesize",25);
    SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(cmd); 
    DataSet ds  = new DataSet();
    da.Fill(ds);
    string htmlData = VuMgr.RenderView("myuc.ascx",(object)ds);
    return htmlData;
}

GETEMPDETAILS stored procedure is used to get the data from the database. SP is optimized to get only the required rows, paging is done at the SP level.

SQL
CREATE PROCEDURE GETEMPDETAILS(
@PAGENO INT, 
@PAGESIZE INT)
AS
BEGIN
    WITH DR(SNO,EMPID,LOGINID,G,M,DOB) 
        AS 
        (SELECT 
            (RANK() OVER(ORDER BY EMPLOYEEID ASC)) AS ROWID, 
            EMPLOYEEID,
            LOGINID,
            GENDER AS G,
            MARITALSTATUS AS M,
            BIRTHDATE AS DOB
        FROM HUMANRESOURCES.EMPLOYEE)
    SELECT SNO,EMPID,LOGINID,G AS GENDER,M AS MARITALSTATUS,DOB AS DATEOFBIRTH
  FROM DR WHERE SNO BETWEEN (((@PAGENO-1) * @PAGESIZE) + 1) 
  AND (@PAGENO * @PAGESIZE)
END

The Web page code goes like this:

ASP.NET
<div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
    <asp:ServiceReference Path="myservice.asmx" />
    </Services>
    </asp:ScriptManager>
    <input type="button" value="Prev" onclick="MovePrev();"/>
    <input type="button" value="Next" onclick="MoveNext();"/>
    <div id="awData"></div>
</div>

This is the script part of the Web page. The pageload function is called when the page is getting loaded. The handler for page load event is attached to the pageload function by default when we use ScriptManager.

C#
//initialize the page number to one for the first time.
var pagenumber = 1;
    
//function called using page load
function pageLoad()
{
    //calling the webservice myservice
    myService.GetEmpDataTable(pagenumber,onResponse);
}
    
//move to next page
function MoveNext()
{
    pagenumber++;
    myService.GetEmpDataTable(pagenumber,onResponse);
}
    
//move to previous page
function MovePrev()
{
    pagenumber--;
    if (pagenumber<1) {alert("this is the first page");pagenumber=1;}
    else
    {myService.GetEmpDataTable(pagenumber,onResponse);}
}
    
//function to call after request is success
function onResponse(response)
{
    //alert(response.length);
    //when the page is beyond the limit the rendered 
    //string will be less than 50 chars.
    if (response.length<50) 
    {   alert("this is the last page");pagenumber--;  }
    else
    { myService.GetEmpDataTable(pagenumber,onResponse); }
    $get("awData").innerHTML = response;
}  

You can visit my blog here.

History

  • 26th October, 2007: Initial post

License

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