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

Cross Page Postbacks on a GridView

Rate me:
Please Sign up or sign in to vote.
4.55/5 (11 votes)
13 Dec 2006CPOL2 min read 56.1K   43   5
This article shows how to do cross page postbacks in a ASP.NET GridView.

Introduction

Have you ever wondered how to do a cross-page postback on a GridView in ASP.NET 2.0? This article shows you how to.

Cross Page Postbacks on a GridView control

In ASP.NET 2.0, with the cross-page postbacks, it is possible to do a post back to a different .aspx page and retrieve the values of the fields of the first page that did the post back.

Thus, I recently had a requirement to display transactions of users on a page (let us call this transactions.aspx) as shown below:

Sample screenshot

Once you have clicked any of the username hyperlinks, it would show a summary of the user on a second page (let us call this usersummary.aspx) as shown below:

Sample screenshot

The above task is a classic example of a cross-browser postback where I do a postback from the GridView of my first page (transactions.aspx) and retrieve the value of the selected (or clicked!!!) user name in my second page (usersummary.aspx).

Let us examine the code below. We will first look at the code of the initial page and then the postback page.

FirstPage (transactions.aspx):

The code for my GridView control is fairly straightforward. Note that my Username column is a ButtonField of type Link and CommandName set to Select.

HTML
<asp:GridView ID="gvTransactions" runat="server" 
   AllowSorting="True" AutoGenerateColumns="False" AllowPaging="True"  
   PageSize="50"  OnRowCommand="gvTransactions_OnRowCommand">   
    <Columns>        
      <asp:ButtonField HeaderText="Username" 
        CommandName="Select" DataTextField="Username" 
        ButtonType="Link"/> 
     <asp:BoundField HeaderText="Date" DataField="Date" />
     <asp:BoundField HeaderText="Description" DataField="Description" />
     <asp:TemplateField HeaderText="Amount (£)" 
          HeaderStyle-HorizontalAlign="Right" 
          ItemStyle-HorizontalAlign="Right">
            <ItemTemplate>
                  <%#Convert.ToDouble(DataBinder.Eval(
                       Container.DataItem,"Amount")).ToString("F")%>
            </ItemTemplate> 
      </asp:TemplateField>    
</Columns>
</asp:GridView>

Also note from above that I have specified the OnRowCommand event which will fire when a row is clicked. Let us examine the event handler code for OnRowCommand.

C#
protected void gvTransactions_OnRowCommand(object sender, 
          GridViewCommandEventArgs e)
{
  if (e.CommandName == "Select")
  {
    int index = Convert.ToInt32(e.CommandArgument);
    GridViewRow selectedRow = (GridViewRow)gvTransactions.Rows[index];

    LinkButton clickedLinkedButton = 
       ((LinkButton)selectedRow.Cells[0].Controls[0]);

    SelectedUserName = clickedLinkedButton.Text;
    Server.Transfer("../../pages/search/usersummary.aspx", true);
  }
}

The key statements in the above code is where I set a Page level property called SelectedUserName with the value selected from the GridView. This is a simple property defined at the Page level of the first page (transactions.aspx) as given below. Also, I do an explicit Server.Transfer into my postback page (usersummary.aspx).

C#
private string _selectedUserName;

public string SelectedUserName
{
get { return _selectedUserName; }
set { _selectedUserName = value; }
}

Now let us look at the postback page (usersummary.aspx). This is a very simple page, and the mechanism of retrieving the value of the selected username (from the first page) is even more simple. Have a look.

PostbackPage (usersummary.aspx):

I first specify the PreviousPageType directive on the top as given below. This is the location of my first page which initiated the postback.

ASP.NET
<%@ PreviousPageType 
   VirtualPath="~/pages/search/transactions.aspx"%>

The PreviousPageType directive provides a way to get strong typing against the previous page, and is accessed through the PreviousPage property.

Now inside the Page_Load event, I retrieve the value of the SelectedUsername from the first page using this.PreviousPage.SelectedUsername as given below:

C#
protected void Page_Load(object sender, EventArgs e)
{
  if (this.PreviousPage != null)
  {
    Response.Write("Bingo!!! I got the selected Username: " + 
                   this.PreviousPage.SelectedUserName);
    ShowUserSummaryDetails(
       this.PreviousPage.SelectedUserName);
  }
}

(Please note that ShowUserSummaryDetails() is my own private function and its code is not relevant for this article.)

Isn't it simple?? Enjoy ASP.NET...Any questions, please feel free to ask.

License

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


Written By
Web Developer
United Kingdom United Kingdom
Siva works as a Senior Consultant for Just Data Services UK Limited (www.justdataservices.com) and works primarily on C#, ASP.NET and related Microsoft Technogies. Originally from Kerala, India he likes spicy food and Indian music.

Comments and Discussions

 
GeneralMy vote of 5 Pin
manoors28-Jul-10 6:03
manoors28-Jul-10 6:03 
good
GeneralWhy not just set a session variable or do a get query Pin
philmee954-Apr-07 13:22
philmee954-Apr-07 13:22 
GeneralPostBackUrl Pin
Gargi Chakravarty16-Feb-07 4:45
Gargi Chakravarty16-Feb-07 4:45 
QuestionPage.IsCrossPagePostBack = false Pin
Fire Dog7-Feb-07 10:27
Fire Dog7-Feb-07 10:27 
AnswerRe: Page.IsCrossPagePostBack = false Pin
CJ Hughes11-Mar-10 15:31
CJ Hughes11-Mar-10 15:31 

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.