Introduction:
I post a lot on Asp.net forums, most of the times answering questions and sometimes asking questions. In this article I will answer some of the most frequently asked questions.
Q1: How do I open a new window from the server side code?
You can open a new window from the server side code by attaching the attributes to the server controls. Let's see that how you can open a new window on the button click event. Just type the line below in the InitializeComponent() method which is automatically generated by Asp.net.
| this.Button1.Attributes.Add("onclick","window.open('http://www.yahoo.com')"); |
This will simply open the webpage for www.yahoo.com. Sometimes you need more flexibility like supplying more attributes to the opened window. Let's see how we can attach more attributes to the new window that opens. Write the following code in the InitializeComponent() of the page.
| string str = @"window.open('http://www.yahoo.com',height=300,width=100,scrollbars=0,toolbar=1)";
this.Button1.Attributes.Add("onclick",str);
|
As you can see that I have placed all the attributes of the window.open into a string and simply supplied the string to the Button1.Attributes.Add method which make our code little bit cleaner.
Q2: How do I iterate through the listbox and find which items have been selected?
Sometimes we have a listbox controls with several values inside it and we want to find that which of those values are selected. Let's see how this can be done.
| foreach(ListItem l in ListBox1.Items)
{
if(l.Selected)
{
Response.Write(l.Value);
}
}
|
As you can see that how simple it is. We are just iterating through the listbox items and when we find an item selected we just print out the value of that particular item.
Q3: How do I pass the values from one page to another?
Passing values from one page to another can be done is many ways hence I will show you two of the most commonly used ways. One will be using QueryString and other will be using Session variables. In both the examples we will be passing values from Page1.aspx to Page2.aspx.
Page1.aspx (QueryString):
| private void Button1_Click(object sender, System.EventArgs e)
{
string myValue = "azamsharp"; // The value being passed
Response.Redirect("Page2.aspx?Name="+myValue);
}
|
Page2.aspx (QueryString):
| if(!Page.IsPostBack)
{
if(Request.QueryString["Name"] != null)
{
string str = Request.QueryString["Name"].ToString();
Response.Write(str);
}
}
|
In Page2.aspx we are first checking that is QueryString is not null and if not than printing out the value in the querystring onto the form.
Now let's see that how we can pass the values from Page1.aspx to Page2.aspx using Session variables.
Page1.aspx (Session)
| private void Button2_Click(object sender, System.EventArgs e)
{
Session["Name"] = "azam";
Response.Redirect("Page2.aspx");
}
|
Page2.aspx (Session):
| // Checking for Session
string myString = Session["Name"].ToString();
Response.Write(myString);
|
Attachments
Project Files Faq Samples