Click here to Skip to main content
15,886,873 members
Articles / Web Development / ASP.NET
Article

DataGrid & Paging using Ajax

Rate me:
Please Sign up or sign in to vote.
3.29/5 (3 votes)
25 Oct 2007CPOL1 min read 32.3K   186   34   3
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)


Written By
Web Developer
India India
Hai, I am a .Net professional just started my career in this field. I like to code more on asp.net. In my spare time, l like to write article and write blogs. i love music and intrested in watching movies.

you can view my blog here.

Comments and Discussions

 
QuestiononResponse locked up in constant loop fix Pin
KentsCode22-Feb-12 8:11
KentsCode22-Feb-12 8:11 
GeneralMy vote of 1 Pin
Member 131539528-Jun-09 22:02
Member 131539528-Jun-09 22:02 
QuestionSorting-n-filtering... Pin
BlackTigerAP29-Oct-07 22:39
BlackTigerAP29-Oct-07 22:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.