Multi-Select and Checked List Box in C# Explained With Example

Updated on December 18, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like video games and reading books.

1. Introduction

In this article Mr. Ax will develop a simple form that uses Combo box, Toggle button-using Checkbox, Multi-Select List Box and Checked List Box. Before he implements it, he will meet his lead Mr.Zx who has the initial design (based on requirement) with him. The requirement given by Mr.Zx is explained below with a screenshot:

Multi-Select and Checked List Box Example - Design (Click to Zoom)
Multi-Select and Checked List Box Example - Design (Click to Zoom) | Source

2. Mr. Zx Explains:

Hey Ax! How are you? I need a form that will be used to assign the work to a salesperson. I contacted our client, and based on their requirement, I had the initial design drawn in the white board [Mr Ax, Looks at the screenshot above]. The top one is a combo box that will list the sales persons working in our client company. Once you pick a person from the list, the person should be displayed on the label stating “Sales assignment for the Person Name”. Also note that user should not be allowed to edit the name of the salesperson in the ComboBox.

Once you select the sales person, now you are ready for assigning the area he or she needs to visit in 2 months. To do that, pick the area from the Visit Area List Box and Move it to the Assigned List Box using the button “>>“. You can also revoke the assigned area by selecting the area from the right and move it to the left List Box using the button “<<”. You must support multiple selections on both sides of the List boxes.

The last stuff is, place the list box which lists all the products that need to be promoted by the salesperson on the assigned area. By default USB Drive item should be selected when the form is displayed. There should be a toggle button, which should be turned ON when the form is displayed reading “Restricted Mode On”. And it should toggle between Restricted Mode On and Restricted Mode Off. When Restricted Mode is turned ON, you should not allow user editing the items Mother Board and USB. This is the task for you in this week. Once you finished, I will move this form to the Database Developer who will link your initial design with the database.

3. Let us start with Form design

To know the form design open the attached project, select each control one by one and look at the properties that appears in Bold. These are all the properties changed from the default by Mr. Ax. I will explain only the important properties set for each control one by one and leaving the other properties for you to explore.

Sales Person ComboBox

1) We set Dropdownstyle property with value DropDownList. This property restricts the user typing their own entry in the edit section of the Combo Box.

2) Next, named of the salesperson are added to the combo box using the Items Property. Mr. Ax knows the other team will populate this combo box from the database. So he prepared the values and added it in the design time of the form.

3) Name Property set to cmbSalesPerson.

Label below the ComboBox

1) Name property changed to lblDisplay.

VisitArea ListBox

1) Name property is set to lstArea

2) Area names are added using Items Property

3) We set SelectionMode property with a value MultiExtended and this allows picking multiple items from it. We can select multiple items in the list box by following these techniques:

  • Hold down the ctrl key and select the items one by one. All the items clicked are selected.
  • Select the first item, hold the shift key, and select another item. Both the List box items are selected and besides that all the items which stays in between them also get selected.
  • Hold the left mouse button on the item and drag the mouse. All the items visited by the mouse pointer get selected.

4) We set Sort Property to true. This is to sort the List Box items.

Button between Two Lists

1) Name property set to btnAssign, btnRevoke

Assigned ListBox

1) Name property is set to lstAssigned

2) Sorted property is set to true

3) The Selection Mode is set to MultiSimple. Now, both the list boxes are supporting multi-Selection. The difference exists on how the multi-select performed. Here, when you click the item it will go to the opposite state. For example, when an item is in a selected state, it goes to unselected state and vice versa.

Checked List box control - Promote Products

1) Name property is set to lstPromote products.

2) CheckOnClick Property is set to true. When it is true, clicking an item will select it and also changes the check mark of item toggles between checked and unchecked.

3) Products are entered into the CheckedListBox using Items Property.

Check box control below the Combo box [it is not button]

1) Name Property set to chkRestricted

2) Appearance Property is set to Button

3) FlatStyle Property is set to System

4. Form Load

Form load event will clear the label lblDisplay and also checks the USB Drive items in the CheckedListBox. Have a look at the Mr. Zx’s expectation. After placing the check mark, the check state of the toggle button is set to Checked State. Below is the code for the Form load event procedure:

//LST_000: Initialize the controls
private void lstBoxes_Load(object sender, 
    EventArgs e)
{
    LblDisplay.Text = "";
    lstPromote_products.SetItemChecked(4, true);
    chkRestricted.Checked = true;
}

5. Salesperson ComboBox

When we change the item in the combo box, SelectedIndexChanged Event is fired. We set the lblDisplay label with the selected person’s Name in side this event procedure. Below is the code for it:

//LST_001: Assign the Selected Persons Name 
//in the Label
private void cmbSalesPerson_SelectedIndexChanged(
    object sender, EventArgs e)
{
    LblDisplay.Text = "Visit Assignment for : " + 
        (string)cmbSalesPerson.SelectedItem ; 
}

6. Assign Button Control in Action

The click event handler of the assign button will move all the selected items from the left ListBox Control to the right ListBox Control. First, we retrieve the selected items using the foreach loop, and then inside loop we ask to add the item to assigned ListBox Control. Remember, both the ListBox Controls has the Sorted Property set to true.

Next, we calculate the total items selected in the Area list box. Then using a for loop we remove all the selected items one by one. The code is given below:

//LST_002: Move all the Selected City to left.
private void btnAssign_Click(object sender, 
    EventArgs e)
{
    //LST_002_01: First add the items to 
    //the Assigned List. 
    foreach (string item in lstArea.SelectedItems)
    {
        lstAssigned.Items.Add(item);
    }

    //LST_002_02:Remove the selected items 
    //from the Area List
    int total = lstArea.SelectedItems.Count;
    for (int x = 0; x < total; x++)
        lstArea.Items.Remove(
            lstArea.SelectedItems[0]);
}

We may have two questions now. 1) Why the SelectedItems Collection is always referred with index 0 while we call the remove function? 2) Why cannot we remove the item in the first foreach loop itself?

For the first question, we are always retrieving the collection from the lstArea. But on each iteration, an item is removed (The selected one) from the selected list. Hence, the index zero has the non-deleted item for removal.

For Second Question, ForEach does not allow the modification to the collection in which it operates on. Hence, we are not removing the items in the first loop.

7. Revoke Button Control in Action

We do similar coding as we did in the previous section. But, here we are moving the items from Right to Left. The code we write as follows:

//LST_003: Revoke all the Selected 
//Assigned area.
private void btnRevoke_Click(object sender, 
    EventArgs e)
{
    //LST_003_01: First add the items to the Area List
    foreach (string item in lstAssigned.SelectedItems)
    {
        lstArea.Items.Add(item);
    }

    //LST_003_02:Remove the selected items 
    //from the Assigned List
    int total = lstAssigned.SelectedItems.Count;
    for (int x = 0; x < total; x++)
        lstAssigned.Items.Remove(
            lstAssigned.SelectedItems[0]);
}

8. CheckBox Acting as Toggle Button

When we change the check state of the check box, an Event called CheckStateChanged is fired. The form handles that event here to change the text of the check box that look like toggle button. Below is the code:

//LST_004: Change the text property based 
//on Check box button state
private void chkRestricted_CheckStateChanged(
    object sender, EventArgs e)
{
    if (chkRestricted.CheckState == 
        CheckState.Checked)
        chkRestricted.Text = "Restricted Mode On";
    else
        chkRestricted.Text = "Restricted Mode Off";
}

9. Lock Specific CheckedListBox Entires

When we place a check mark or remove it from the item, Dotnet Framework fires ItemCheck Event. Also, the argument ItemCheckEventArgs passed to this Event handler will have NewValue and CurrentValue as properties. For example, if we click an item which is already in the Checked State then, NewValue is UnChecked and Current Value is Checked.

So the code below checks the Restricted Mode toggle button’s state and resets the NewValue with CurrentValue, there by keeping the item in the same state. In end user point of view, the items are in locked for modification. Below is the code for it:

//LST_005: Make sure check state change 
//performed for Mother board and usb drives. 
//If so do not allow the state change 
//when restricted Mode is turned-on.
private void lstPromote_products_ItemCheck(
    object sender, ItemCheckEventArgs e)
{
    //LST_005_01: Do nothing when 
    //restricted mode is OFF
    if (chkRestricted.CheckState == 
        CheckState.Unchecked)
            return;

    //LST_005_02: Get the Checked item
    string selected_product = (string) 
        lstPromote_products.Items[e.Index];

    if (
        selected_product == "Pentium Mother Board" 
        ||
        selected_product == "USB Drives"
        )
            e.NewValue = e.CurrentValue;
}

Source Code Example: Download

This example is created using VS 2005 IDE.

Questions & Answers

    © 2018 sirama

    Comments

      0 of 8192 characters used
      Post Comment

      No comments yet.

      working

      This website uses cookies

      As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

      For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

      Show Details
      Necessary
      HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
      LoginThis is necessary to sign in to the HubPages Service.
      Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
      AkismetThis is used to detect comment spam. (Privacy Policy)
      HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
      HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
      Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
      CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
      Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
      Features
      Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
      Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
      Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
      Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
      Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
      VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
      PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
      Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
      MavenThis supports the Maven widget and search functionality. (Privacy Policy)
      Marketing
      Google AdSenseThis is an ad network. (Privacy Policy)
      Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
      Index ExchangeThis is an ad network. (Privacy Policy)
      SovrnThis is an ad network. (Privacy Policy)
      Facebook AdsThis is an ad network. (Privacy Policy)
      Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
      AppNexusThis is an ad network. (Privacy Policy)
      OpenxThis is an ad network. (Privacy Policy)
      Rubicon ProjectThis is an ad network. (Privacy Policy)
      TripleLiftThis is an ad network. (Privacy Policy)
      Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
      Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
      Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
      Statistics
      Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
      ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
      Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
      ClickscoThis is a data management platform studying reader behavior (Privacy Policy)