AIM: Design a web application using Dropdown List and List Box using ASP.Net through C# language.
Here, the aim is to design a web application using dropdown list and listbox. To understand the concept of these controls, we have taken an example of "Date Picker" to make understanding of dropdown list and "Subject Selection" to make understanding on List Box.
First let us understand,
Design view of DatePicker using DropDownList is shown in Figure 2. Here, we have placed three DropDownList, one for to select day, one for month and one for year. Selected date from DropDownList will be shown on TextBox when clicking on Button.
Now, there are two ways to store values in dropdownlist, fixed and dynamic. First let us understand how we can store fixed values in dropdownlist.
Let store months in middle dropdownlist (DropDownList2), for this we have to click DropDownList2 Task as shown in Figure 3 (a) and Click on Edit Items. Now Add number of items, you want to add in dropdownlist and edit text property of each item as shown in Figure 3 (b).
Now, to store dynamic values at run time in DropDownList1 having all days and DropDownList3 having all years. Code for DropDownList1 and DropDownList3 is shown below. The code get executed when page loaded first time.
C# code to store days and years in drop down list:
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { DropDownList1.Items.Add(new ListItem("------Day------")); for (int i = 1; i <= 31; i++) { DropDownList1.Items.Add(new ListItem(i.ToString())); } DropDownList3.Items.Add(new ListItem("------Year------")); for (int i = DateTime.Now.Year - 50; i <= DateTime.Now.Year; i++) { DropDownList3.Items.Add(new ListItem(i.ToString())); } } }
Now, to get the selected date, from drop down lists following code is to be done that get executed on button click.
protected void Button1_Click(object sender, EventArgs e) { TextBox1.Text = DropDownList1.Text + "/" + DropDownList2.SelectedValue.ToString() + "/" + DropDownList3.SelectedItem.Text; }