Sunday, February 24, 2008

Passing Values between Web Pages (Beginner)

During a coffee break at work, I was explaining my friend how I had used a Wizard control in my Web App for the User registration process and had saved myself from headaches involving passing data between pages, storing user selection of choices in each page etc. My friend was pretty impressed with what the Wizard control could achieve and commended Scott & his team at Redmond for making things simple for programmers. "Developing Web Apps is pretty challenging compared to a Windows Application. And that is the sex appeal of developing Web Apps.."

True!! I started to wonder about the difference in approach between a Web App and a Windows Application. In case of a windows application passing data between 2 forms is a piece of cake. But how do I pass values between web pages? I was sure that it wasn't something very complex, but I realized that it was something I did not know. So I decided to try that and did so in a matter of minutes. Thanks to the documentation and example at msdn! This is what I did.

1. I created a new website with 2 pages Default.aspx and Default2.aspx

2. In Default.aspx I added a Textbox and a button.

3. In Default2.aspx I added a Label. My Objective was to display text entered in the text box in the label on click of the button.

4. I set the PostbackUrl of button to Default2.aspx

ID="Button1" runat="server" Text="Button" PostBackUrl="~/Default2.aspx"


5. Next I write the following code in the page load of Default2.aspx

if (Page.PreviousPage != null)
{
TextBox SourceTextBox = (TextBox)Page.PreviousPage.FindControl("TextBox1");

if (SourceTextBox != null)
{
Label1.Text = SourceTextBox.Text;
}
}


6. And that's it! The value of the text box is passed onto the Label on the second page.

This is one of the many ways of passing data between pages. I will explore and post about them in the coming weeks.

Till Then Happy Programming !!

No comments:

Post a Comment