Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Common Dropdownlist Operation in ASP.NET and C#

In this article, you will learn to make a sample application that will help you to perform most common operations with dropdown using the ASP.NET and C#.

Introduction:

ASP.NET DropDownList is one of the commonly used control in ASP.NET. This article discuss the different operations with DropDownList.

Lets start with the ASP.Net and add different controls in ASP Page.

Add a DropDownList with name “cmbLanguages” which is main dropdown in this page.

Listing 1: DropDownList cmbLanguages

<asp:DropDownList ID="cmbLanguages" runat="server" AutoPostBack="True" 
            onselectedindexchanged="cmbLanguages_SelectedIndexChanged">
        </asp:DropDownList>

This dropdown have AutoPostBack="True" which specify that page will post back whenever there is any selection change in DropDownList. There is attached event “onselectedindexchanged”, Will get called whenever there is selection change in dropdown. After the selection change the page will postback and call “cmbLanguages_SelectedIndexChanged” event.

Define another dropdown list called “cmbPrograms” which will fill on button click.

Listing 2: DropDownList cmbPrograms

<asp:DropDownList ID="cmbPrograms" runat="server">
        </asp:DropDownList>

Define different buttons, which will perform different operations with DropDownList:

ReFill Data - Refill the data in DropDownList.

Remove Data - Remove the first item from DropDownList.

Add Data - Add a item in DropDownList.

Sort Data - Sort the items of DropDownList.

Populate Programs - Populate the second dropdown by taking input from first one.

ASP.NET Code:

Listing 3: ASP.NET Code

<div>
    <form id="form1" runat="server">
    <p>
        Programming Languages:
        <asp:DropDownList ID="cmbLanguages" runat="server" AutoPostBack="True" 
            onselectedindexchanged="cmbLanguages_SelectedIndexChanged">
        </asp:DropDownList>
    </p>
    <p>
        Programs
<asp:DropDownList ID="cmbPrograms" runat="server">
        </asp:DropDownList>
    </p>
    
        OutPut
<asp:Label ID="lblOutput" runat="server"></asp:Label>
    </p>
    <p>
        <asp:Button ID="btnFillData" runat="server" onclick="btnFillData_Click" 
            Text="ReFill Data" />
 <asp:Button ID="btnRemoveData" runat="server" onclick="btnRemoveData_Click" 
            Text="Remove Data" />
 <asp:Button ID="btnAddData" runat="server" onclick="btnAddData_Click" 
            Text="Add Data" />
 <asp:Button ID="btnSortData" runat="server" onclick="btnSortData_Click" 
            Text="Sort Data" />
     <asp:Button ID="btnPopulatePrograms" runat="server" onclick="btnPopulatePrograms_Click" 
            Text="Populate Programs" />
    </p> 
    </div>

Lets now discuss the C# Code to perform these operations.

Dummy Dataset:

The below function is used to create a dummy dataset, which is further used for filling the language dropdown. This is simple C# code to first create dataset “objDS” and then create a datatable “objTable” and then add the columns “Language_ID” and “Language_Name”.

After creating the structure, fill the data in dataset by

Listing 4: DataSet - Add Row

objTable.Rows.Add(1, "C#.NET");
 

Listing 5: Dummy DataSet

private DataSet LanguageList()
    {
        //Create a new Dataset
        DataSet objDS = new DataSet();
        //Create a new datatable
        DataTable objTable = objDS.Tables.Add();

        //Add coloms
        objTable.Columns.Add("Language_ID", typeof(int));
        objTable.Columns.Add("Language_Name", typeof(string));

        //Add rows
        objTable.Rows.Add(1, "C#.NET");
        objTable.Rows.Add(2, "VB.NET");
        objTable.Rows.Add(3, "ASP.NET");
        objTable.Rows.Add(4, "PHP");
        objTable.Rows.Add(5, "JAVA");
        objTable.Rows.Add(6, "C++");
        objTable.Rows.Add(7, "Java Script");

        return objDS;
    }

Populate the cmbLanguages DropDownList on Page load:

Page_Load is called when page loads. IsPostBack property is false only when the page load first time. So the code inside this function will execute only once after the page open.

Original Programming Language Combo

Figure 1: Original Programming Language Combo

The Page_load get the dummy dataset by calling LanguageList() method. To fill dataset data into dropdown assign value field and text field to cmbLanguages. Please note that DataTextField is display field and DataValueField is value field.

Listing 6: DropDownList Value and Text Field

cmbLanguages.DataValueField = "Language_ID";
cmbLanguages.DataTextField = "Language_Name";

Now assign the dataset to combo and use DataBind() method to bind the dataset. Note that the dropdown will not display data until it is not bind.

Listing 7: DropDownList - Databind

cmbLanguages.DataSource = oDs;
cmbLanguages.DataBind();

Listing 8: Page_Load Event

protected void Page_Load(object sender, EventArgs e)
    {
        //Fill only first time of page load
        if (!IsPostBack)
        {
            DataSet oDs = LanguageList();

            if (oDs != null && oDs.Tables != null)
            {
                cmbLanguages.DataValueField = "Language_ID";
                cmbLanguages.DataTextField = "Language_Name";

                //Assign the dataset to dropdown list
                cmbLanguages.DataSource = oDs;
                cmbLanguages.DataBind();
            }
        }
    }   

Remove Items from Dropdown:

Dropdown List After Removing Items

Figure 2: Dropdown List After Removing Items

To remove data from dropdown there is two popular methods:

  1. Remove the item - To use this method first find the item and cmbLanguages.Items.Remove(itemToRemove);
  2. Remove by passing index - just pass the index and the method will remove the item. cmbLanguages.Items.RemoveAt(0);

Listing 9: Remove Items

protected void btnRemoveData_Click(object sender, EventArgs e)
    {
        //Remove item by name
        //if(itemToRemove != null)        
        //ListItem itemToRemove = cmbLanguages.Items.FindByText("ASP.NET");
        //cmbLanguages.Items.Remove(itemToRemove);

        //Remove item from perticular location
        if(cmbLanguages.Items.Count > 0)
         cmbLanguages.Items.RemoveAt(0);
    }

Add Items in Dropdown:

Create an item by passing the value text for the item. new ListItem("C-" + intNewIndex.ToString(), intNewIndex.ToString()); To Add an item in dropdown use the following command: cmbLanguages.Items.Add(liLanguage);

Dropdown List After Adding Items - C4, C5, C6

Figure 3: Dropdown List After Adding Items - C4, C5, C6

Listing 10: Add Items

protected void btnAddData_Click(object sender, EventArgs e)
    {
        //Add data to list
        int intNewIndex = cmbLanguages.Items.Count + 1;

        ListItem liLanguage = new ListItem("C-" + intNewIndex.ToString(), intNewIndex.ToString());
        cmbLanguages.Items.Add(liLanguage);
        
    }

Sort the items of dropdown:

To sort the items of dropdown read all items in arraylist and use the “TextArray.Sort()” method to sort the items. Please note that sorting text items does not mean that value items will sort automatically. You have to first sort the text items and the find the corresponding value items and add manually in separate arraylist.

Once you get the sorted values of text and value separately clear the dropdown by cmbLanguages.Items.Clear();

Now add these items one by one in dropdown again.

Dropdown List After Sorting

Figure 4: Dropdown List After Sorting

Listing 11: Sort Items

protected void btnSortData_Click(object sender, EventArgs e)
    {       
        ArrayList TextArray = new ArrayList();
        ArrayList ValueArray = new ArrayList();


        foreach (ListItem li in cmbLanguages.Items)
        {
            TextArray.Add(li.Text);
        }

        TextArray.Sort();


        foreach (object itemArray in TextArray)
        {
            string value = cmbLanguages.Items.FindByText(itemArray.ToString()).Value;
            ValueArray.Add(value);
        }
        cmbLanguages.Items.Clear();

        for (int i = 0; i < TextArray.Count; i++)
        {
            ListItem objItem = new ListItem(TextArray[i].ToString(), ValueArray[i].ToString());
            cmbLanguages.Items.Add(objItem);
        }      

    }

ReFill dropdown:

There is separate event in this page to refill the dropdown with the original values. This is same code used in page load. In this method you don’t have to clear the values of dropdown because assigning the separate dataset as it is replacing the previous values.

Dropdown List After Refilling

Figure 5: Dropdown List After Refilling

Listing 12: Repopulate Items

protected void btnFillData_Click(object sender, EventArgs e)
    {
        DataSet oDs = LanguageList();

        cmbLanguages.DataValueField = "Language_ID";
        cmbLanguages.DataTextField = "Language_Name";

        cmbLanguages.DataSource = oDs;
        cmbLanguages.DataBind();
    }
 

SelectedIndexChanged event of Dropdown:

This event occure when there is any change in dropdown. If you select a different value it will execute. The output you can see the Output lable.

Also you can populate the other dropdown on selection change (See Commented code)

Dropdown List After SelectedIndexChanged

Figure 6: Dropdown List After SelectedIndexChanged

Listing 13: Dropdown - SelectedIndexChanged

  protected void cmbLanguages_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblOutput.Text = cmbLanguages.SelectedItem.Text;
        
        //Can fill the other dropdown on selection change of first dropdown
        //PopulatePrograms();
    }

Populate Another Dropdown:

This method takes input from cmbLanguages and populate another dropdown cmbPrograms.

Pupulate Programs Dropdown Depending on Selected Values of Programming Language Dropdown

Figure 7: Pupulate Programs Dropdown Depending on Selected Values of Programming Language Dropdown

Listing 14: Dropdown - Populate another dropdown

private void PopulatePrograms()
    {
        if (cmbLanguages.Items.Count > 0)
        {
            int intNewIndex = cmbPrograms.Items.Count + 1;

            ListItem liLanguage = new ListItem(cmbLanguages.SelectedItem.Text + " Program #" + intNewIndex.ToString(), intNewIndex.ToString());
            cmbPrograms.Items.Add(liLanguage);

            intNewIndex++;
            liLanguage = new ListItem(cmbLanguages.SelectedItem.Text + " Program #" + intNewIndex.ToString(), intNewIndex.ToString());
            cmbPrograms.Items.Add(liLanguage);

        }
    }


I am having total 7+ years of experience in developing applications using C#, VB.NET, ASP.NET, Silverlight, WCF, SQL Server and Oracle. I am holding a M.Tech degree in Intelligent systems. For more information, visit my Linkedin p...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login