Click here to Skip to main content
6,822,123 members and growing! (17,734 online)
Email Password   helpLost your password?
Web Development » Ajax and Atlas » General     Intermediate License: The Code Project Open License (CPOL)

DataGrid & Paging using Ajax

By asithangae

Achieving the DataGrid functionality with paging using User control and Ajax
Javascript, XML, C#2.0.NET2.0, WinXP, ASP.NET, Ajax, SQL2005, VS2005, DBA, Dev
Posted:25 Oct 2007
Views:13,401
Bookmarked:30 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
3 votes for this article.
Popularity: 1.57 Rating: 3.29 out of 5
1 vote, 33.3%
1

2
1 vote, 33.3%
3

4
1 vote, 33.3%
5

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.

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:

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:

[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.

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:

<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.

//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)

About the Author

asithangae


Member
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.
Occupation: Web Developer
Location: India India

Other popular Ajax and Atlas articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
GeneralMy vote of 1 PinmemberMember 131539523:02 28 Jun '09  
QuestionSorting-n-filtering... PinmemberBlackTigerAP23:39 29 Oct '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 25 Oct 2007
Editor: Deeksha Shenoy
Copyright 2007 by asithangae
Everything else Copyright © CodeProject, 1999-2010
Web09 | Advertise on the Code Project