dynamic dropdown lists 1. objectives you will be able to use dropdown lists to solicit multiple...

Post on 13-Jan-2016

222 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Dynamic Dropdown Lists

1

Objectives

You will be able to Use Dropdown Lists to solicit multiple choice user input in an ASPX web page. Populate a Dropdown List at run time using data from a file.

2

DropDownList

The ASPX DropDownList generates an HTML Select control.

A good way to get a user input from an extensive set of discrete choices.

The list should not be too long. If there are many choices divide it into

subsets. Use one DropDownList to select the subset. Use a second DropDownList to select from the

subset. Second DropDownList must be dynamically

populated based on choice from the first.3

Example

Select a city from a list of 275 largest US cities and display its population.

Let first DropDownList select a state. Second DropDownList includes just the

cities in that state.

4

Largest US Cities

http://en.wikipedia.org/wiki/List_of_United_States_cities_by_population

5

Data File

Download to desktop: http://www.cse.usf.edu/~turnerr/Web_Application_Design/Downl

oads/

File cities.csv

6

7

Dropdown List Demo Create a new C# ASP.NET empty web site.

Name: Dropdown_List_Demo

Add Default.aspx

8

Add Default.aspx

9

Add New Folder

10

New Folder for the Data File In Visual Studio

Rename the new folder App_Data. Note: This name is significant.

Open the App_Data folder in the website folder and copy the downloaded file cities.csv into it.

11

The App_Data Folder

12

Add Data File to the Project

Back in Visual Studio, right click on App_Data and add the file cities.csv to the project.

13

Add cities.csv to the Project

Select “All Files”

cities.csv in the Project

15

16

Class City

Let’s create a class to hold information about a city.

An Entity class Frequently used to create objects corresponding to

information in a database.

Object-Relational Mapping http://en.wikipedia.org/wiki/Object-relational_mapping

Automated tools are available Best to do manually until you have a thorough understanding.

(This is an especially simple example.)

17

Class City

Add Class City

18

Add Class City

19

Class Cityusing System;

public class City : IComparable<City>

{

public int rank;

public String name;

public String state;

public int population;

public City(string line)

{

string[] info;

info = line.Split(',');

rank = int.Parse(info[0]);

name = info[1];

state = info[2];

population = int.Parse(info[3]);

}

public int CompareTo(City other)

{

int result = string.Compare(this.state, other.state);

if (result == 0)

{

result = string.Compare(this.name, other.name);

}

return result;

}

}

20

In order for us to use the sort method for List<City>, the City class must implement the IComparable<City> interface and provide a CompareTo method.

Design the Page

21

ddlState ddlCity

Read the Data

On Page_Load Read the file cities.csv Create a City object from each line. Add the City objects to a list. Sort the list by state name then city

name. Save the list as an Application variable. Populate the State Dropdown List.

It will never change.

22

Default.aspx.cs

using System;

using System.IO;

using System.Collections.Generic;

using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page

{

List<City> cities = new List<City>();

23

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)

{

if (Application["cities"] == null)

{

string path = Server.MapPath("App_Data/cities.csv");

using (StreamReader readFile = new StreamReader(path))

{

string line;

while ((line = readFile.ReadLine()) != null)

{

City city = new City(line);

cities.Add(city);

}

}

cities.Sort();

Application["cities"] = cities;

}

else

{

cities = (List<City>)Application["cities"];

}24

Default.aspx.cs (continued)

if (IsPostBack)

{

return;

}

// Initial page load only

ListItem li = new ListItem("", "");

ddlState.Items.Add(li);

string prev_state = "";

foreach (City city in cities)

{

if (city.state != prev_state)

{

// Add state to dropdown list.

li = new ListItem(city.state, city.state);

ddlState.Items.Add(li);

prev_state = city.state;

}

}

25Build and run.

Dropdown_List_Demo in Chrome

26

Note scrollbar on Dropdown List

Add Event Handler

When the user selects a state, populate the City list with cities in that state.

Need an event handler for Selected Index Changed.

Double click on the States Dropdown List in the designer. Visual Studio adds event handler to

Default.aspx.cs27

SelectedIndexChanged Event Handler

Start with a stub.

protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)

{

string selected_state = ddlState.SelectedValue;

lblPopulation.Text = "You selected " + selected_state;

}

Try it!

28

Page in Chrome

29

State selected.

Nothing happens!

What’s wrong?

Nothing Happens

There is no postback when an item is selected from ddlState.

We need AutoPostback.

30

Set AutoPostBack

31Try again

Works as Expected

32

Add code to populate the City DropDownList.

Populate ddlCity

protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)

{

string selected_state = ddlState.SelectedValue;

ddlCity.Items.Clear();

ListItem li = new ListItem("", "");

ddlCity.Items.Add(li);

foreach (City city in cities)

{

if (city.state == selected_state)

{

li = new ListItem(city.name, city.name);

ddlCity.Items.Add(li);

}

}

}

33

ddlCity Populated

34

Add a SelectedIndexChanged event handler for ddlCity and set AutoPostBack.

ddlCity Event Handler

protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)

{

int population = 0;

foreach (City city in cities)

{

if (city.name == ddlCity.SelectedValue)

{

population = city.population;

break;

}

}

lblPopulation.Text =

"Population of " + ddlCity.SelectedValue + " is " +

population.ToString();

}

35

Try it!

Select Tampa

36

Result

37

A Rough Edge

When we select a new state, the previous city population stays on the page until we select a new city.

Solution: Clear the label on

SelectedIndexChanged.

38

A Minor Bug

What happens if user selects the blank entry at the beginning of the list? (after selecting a nonblank entry)

39

A Minor Bug

40

Solution

Check for this and ignore the event.protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)

{

lblPopulation.Text = "";

if (ddlState.SelectedIndex == 0)

{

return;

}

...

protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)

{

lblPopulation.Text = "";

if (ddlCity.SelectedIndex == 0)

{

return;

}

...

41

Works as Expected

42

Blank initial item selected.

Summary We can populate a DropDownList with

information determed at run time. Contents of a file. Information determined by user input.

If we need an immediate action when the user selects an item, set AutoPostBack to true.

End of Presentation

43

top related