Web Applications Example Topics

 

Code: Adding Items to a List Control

This example uses the Add method of the ListBox.Items property to add items to the list.

Example

// Create a string array and assign items.

string[] ListContents = {“Enju”, “Sue”, “Mary”};

 

// Add the array items to the list box.

for (int i = 0; i <= ListContents.Length – 1; i++)

ListBox1.Items.Add(ListContents[i]);

Code: Removing Items From a List Control

This example uses the Remove method of the ListBox.Items property to remove an item from the list.

Example

ListBox1.Items.Remove(“Mary”);

Compiling the Code

Start a new ASP.NET Web application and do the following:

  • Add a list box named ListBox1.
  • Copy the code and paste it into the Page_Load method.

Code: Determining the Selected Item in a List Control

This example uses the SelectedIndex and SelectedItem properties of a List control to access information about the selected item.

Example

// The index:

int ListItemIndex;

// Value of the item:

string ListItemValue;

 

ListItemIndex = ListBox1.SelectedIndex;

ListItemValue = ListBox1.SelectedItem.Value.ToString();

Code: Selecting an Item in a List Control

This example uses the IndexOf method to search a list box for a specific text.

ListBox1.SelectedIndex = ListBox1.Items.IndexOf(ListBox1.Items.FindByText(“ValueToFind”));

 

Code: Adding Controls at Run Time

This example adds a text box and button to a Web Forms page at run time. It also dynamically binds an event handler to the button’s Click event. The handler displays the values of the dynamically generated text box.

The controls are added into a Panel Web server control, which acts as a placeholder. The controls are separated in the panel with line breaks (HTML <BR> elements), which are added to the panel using the LiteralControl control.

Example

private void Page_Load(object sender, System.EventArgs e)

{

if (!IsPostBack)

AddControls();

}

protected override void LoadViewState(object savedState)

{

base.LoadViewState(savedState);

if (ViewState[“controsladded”] == null)

AddControls();

}

private void AddControls()

{

TextBox dynamictextbox = new TextBox();

dynamictextbox.Text = “(Enter some text)”;

dynamictextbox.ID = “dynamictextbox”;

Button dynamicbutton = new Button();

dynamicbutton.Click += new System.EventHandler(dynamicbutton_Click);

dynamicbutton.Text = “Dynamic Button”;

Panel1.Controls.Add(dynamictextbox);

Panel1.Controls.Add(new LiteralControl(“<BR>”));

Panel1.Controls.Add(new LiteralControl(“<BR>”));

Panel1.Controls.Add(dynamicbutton);

ViewState[“controlsadded”] = true;

}

private void dynamicbutton_Click(Object sender, System.EventArgs e)

{

TextBox tb = new TextBox();

tb = (TextBox) (Panel1.FindControl(“dynamictextbox”));

Label1.Text = tb.Text;

}

Code: Displaying Data in a Web Forms DataGrid Control

This example uses the DataBind method to bind the contents of a dataset to a DataGrid control.

Example

if (!IsPostBack)

{

sqlDataAdapter1.Fill(dataSet11);

DataGrid1.DataBind();

}

Compiling the Code

This example requires:

  • A Web Forms page.
  • A DataGrid control named DataGrid1.
  • A typed dataset named dataSet11, which is an instance of the typed dataset class DataSet1.
  • A properly configured data adapter named sqlDataAdapter1. You can bind the DataGrid control to any Web Forms page data source.
  • The application must have permission to access the database. For details, see Using SQL Server in Web Applications.

Robust Programming

You can specify the DataGrid control’s DataSource property at design time in the Properties window. You do not have to specify it at run time, as is shown in the previous example.

You should always wrap data access calls in a try-catch block:

try

{

sqlDataAdapter1.Fill(dataSet11);

DataGrid1.DataBind();

}

catch

{

Label1.Text = “Unable to connect to the database.”;

}

You should bind the DataGrid control to its data source only when there is a change to the data or to the control’s state. Do not data bind the control on each round trip. In the previous example, the control is bound only the first time the page runs, not on every postback.

Web Forms pages often benefit by caching a dataset rather than requerying the database

Code: Passing Data from One Web Forms Page to Another

This example stores information in session state and navigates to another page in the same application, then retrieves the stored information in the second page.

Example

// First part: Saves info on first page.

string firstName = “John”;

string lastName = “Smith”;

string city = “Seattle”;

Session.Add(“First”, firstName);

Session.Add(“Last”, lastName);

Session.Add(“City”, city);

 

// Redirect to second page.

Server.Transfer(“WebForm2.aspx”);

 

// Second part: Reads info into variables on the second page.

string firstName = (string)(Session[“First”]);

string lastName = (string)(Session[“Last”]);

string city = (string)(Session[“City”]);

 

Compiling the Code

  • Start an ASP.NET application with two Web Forms pages, WebForm1.aspx and WebForm2.aspx.
  • Paste the first part of the code into the Page_Load method (or a Click method) of WebForm1.aspx.
  • Paste the second part of the code into the Page_Load method of WebForm2.aspx.

 

Code: Writing a Cookie

The following example uses the HttpCookie class and its properties to write a cookie that expires after one minute.

Example

HttpCookie myCookie = new HttpCookie(“MyTestCookie”);

DateTime now = DateTime.Now;

 

// Set the cookie value.

myCookie.Value = now.ToString();

// Set the cookie expiration date.

myCookie.Expires = now.AddMinutes(1);

 

// Add the cookie.

Response.Cookies.Add(myCookie);

 

Response.Write(“<p> The cookie has been written.”);

Code: Reading a Cookie

The following example uses the HttpCookie class and its properties to read a cookie with a specific name.

Example

HttpCookie myCookie = new HttpCookie(“MyTestCookie”);

myCookie = Request.Cookies[“MyTestCookie”];

 

// Read the cookie information and display it.

if (myCookie != null)

Response.Write(“<p>”+ myCookie.Name + “<p>”+ myCookie.Value);

else

Response.Write(“not found”);

Compiling the Code

Start a new ASP.NET Web application and paste the code into the Page_Load method.

Robust Programming

Replace the name “MyTestCookie” with the name of the cookie to be read.

Values returned from a cookie are always of type string.

 

 

Code: Reading Values From Application State

This example retrieves a value from the HttpApplicationState object.

Example

string appMsg;

appMsg = (string)(Application[“Message”]);

Compiling the Code

Start a new ASP.NET application and paste the code into the Page_Load method.

Robust Programming

You must cast the data to the appropriate type, as shown in the example.

No exception is thrown if you attempt to get a value out of application state that does not exist. To be sure that the value you want is in application state, check first for the existence of the object with a test such as the following:

if (Application[“Message”] == null)

Response.Write(“No such value in application state.”);

If you attempt to use a non-existent application state entry in some other way (for example, to examine its type), a NullReferenceException exception is thrown

Code: Reading Values From Session State

This example accesses the HttpSessionState.Item property to retrieve the values in session state.

Example

string firstName = (string)(Session[“First”]);

string lastName = (string)(Session[“Last”]);

string city = (string)(Session[“City”]);

Compiling the Code

Start a new ASP.NET application and paste the code into the Page_Load method.

Robust Programming

Session values are of type Object. You should cast to the appropriate type when reading them.

No exception is thrown if you attempt to get a value out of session state that does not exist. To be sure that the value you want is in session state, check first for the existence of the object with a test such as the following:

if (Session[“City”] == null)

Response.Write(“No such value in session state.”);

If you attempt to use a non-existent session state entry in some other way (for example, to examine its type), a NullReferenceException exception is thrown.

Code: Reading a Value From View State

This example saves the value “yellow” to the Control.ViewState property and then, when the page posts back to the server, retrieves a value of the property. For more information on ViewState, see Saving Web Forms Page Values Using View State.

Example

string strColor;

if (Page.IsPostBack)

{

// Retrieve and display the property value.

strColor = (string)ViewState[“color”];

Response.Write(strColor);

}

else

// Save the property value.

ViewState[“color”] = “yellow”;

Compiling the Code

Copy and paste the code into the Page_Load method of an ASP.NET Web application.

Robust Programming

As shown in the example, retrieving the ViewState property occurs when the Web page is posted back to the server. Otherwise, the string will be null.

For more information on usage recommendations, see State Management Recommendations.

 

 

 

Code: Retrieving a Dataset from View State

This example retrieves the DataSet from a view state.

if (Page.IsPostBack)

{

System.IO.StringReader sr =

new System.IO.StringReader((string)(ViewState[“dSet”]));

dSet.ReadXml(sr);

}

Compiling the Code

Start a new ASP.NET Web application and do the following:

  • Add a DataAdapter named SqlDataAdapter1.
  • Generate a DataSet (the default name of the DataSet class is DataSet1).
  • Create an instance of DataSet1 named dSet.
  • Copy the code and paste it into the Page_Load method.

Code: Redirecting to Another Page

This example uses the HttpResponse.Redirect method to redirect the browser to the specified URL.

Response.Redirect(“http://www.microsoft.com&#8221;);

Code: Redirecting to Another Page in the Same Application

This example uses the Server.Transfer method to redirect the browser to the specified page.

Server.Transfer(“WebForm2.aspx”);

Code: Saving Values in Application State

This example uses the HttpApplicationState class to save global information.

Example

Application[“Message”] = “AppMsg”;

Application[“AppStartTime”] = DateTime.Now;

 

Code: Saving Values in Session State

This example uses the Session.Add method to persist values within an individual session.

Example

string firstName = “Jeff”;

string lastName = “Smith”;

string city = “Seattle”;

 

Session.Add(“First”, firstName);

Session.Add(“Last”, lastName);

Session.Add(“City”, city);

Compiling the Code

Start a new ASP.NET application and paste the code into the Page_Load method.

Code: Saving a Dataset to View State

This example uses the Control.ViewState property to save a dataset.

Example

sqlDataAdapter1.Fill(dSet);

System.IO.StringWriter sw = new System.IO.StringWriter();

 

// Write the DataSet to the ViewState property.

dSet.WriteXml(sw);

ViewState[“dSet”] = sw.ToString();

Compiling the Code

Start a new ASP.NET Web application and do the following:

  • Add a DataAdapter named SqlDataAdapter1.
  • Generate a dataset and then create an instance named dSet.
  • Copy the code and paste it into the Page_Load method.

Code: Saving a Value in View State

This example saves the string value “yellow” to the Control.ViewState property. For more information, see Saving Web Forms Page Values Using View State.

ViewState[“color”] = “yellow”;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s