When working with websites, you often need to pass values from one page to
another like data from html page to aspx web forms in context of Asp.Net
For example in first page you collect
information about your client, first name and last name and use this information
in your second page.
For passing variables content between
pages ASP.NET gives us several choices. One choice is using QueryString property of Request Object. When surfing internet you should
have seen weird internet address such as one below.
http://www.localhost.com/Webform2.aspx?Firstname=Sumit&LastName=Kesarwani
This html addresses
use QueryString property to pass values between pages. In this address you send
3 information.
Webform2.aspx this is the page your browser will go.
Firstname=Sumit you send a Firstname variable which is set
to Sumit
LastName=Kesarwani you send a Lastname variable which is set to
Kesarwani
As you have guessed ? starts
your QueryString, and & is used between variables.
Example
Step 1:-
Design the form as shown below:
|
<div>
<table>
<tr>
<td>
Firstname
</td>
<td>
<asp:TextBox
ID="txtFirstname"
runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Lastname
</td>
<td>
<asp:TextBox
ID="txtLastname"
runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button
ID="btnSend"
runat="server"
Text="Send Values"
onclick="btnSend_Click"
/>
</td>
</tr>
</table>
</div>
|
Step 2:-
Write the following code in webform1.aspx.cs
|
using
System;
namespace
QueryStringWebApplication
{
public
partial
class
WebForm1 :
System.Web.UI.Page
{
protected void
Page_Load(object sender,
EventArgs e)
{
}
protected void
btnSend_Click(object sender,
EventArgs e)
{
Response.Redirect("WebForm2.aspx?Firstname=" +
txtFirstname.Text + "&Lastname="
+ txtLastname.Text);
}
}
}
|
Step 3:-
Add another form webform2.aspx
|
<div>
Firstname : <asp:Label
ID="lblFirstname"
runat="server"></asp:Label>
<br/>
Lastname : <asp:Label
ID="lblLastname"
runat="server"></asp:Label>
</div>
|
Step 4:-
Write the following code in webfrom2.aspx.cs file
|
using
System;
namespace
QueryStringWebApplication
{
public
partial
class
WebForm2 :
System.Web.UI.Page
{
protected
void
Page_Load(object
sender, EventArgs e)
{
if (!IsPostBack)
{
lblFirstname.Text = Request.QueryString["Firstname"];
lblLastname.Text = Request.QueryString["Lastname"];
}
}
}
}
|
Step 5:-
Run the application
After filling the values click on the send values button
It will redirect to you on webform2.aspx page and show the message like this.
And also you can see that the values passed are on the URL.
No comments:
Post a Comment