ARTICLE

Checked List Box and Multi-Select List Box

Posted by Sivaraman Dhamodaran Articles | Visual C# December 13, 2010
In this Article we will explore Multi-select List box and Checked List box with some other Controls.
Reader Level:
Download Files:
 

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 starts implementing it, he is going to 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 the screen shot:

 Pic01.JPG

2. Mr.Zx explains:

Hey Ax! How are you? I need a form that will be used to assign the work for sales person. I contacted our client, and based on their requirement I had the initial design drawn in the white board [Mr Ax, Looks at the screen shot above]. The top one is combo box that will list the sales persons working on our client company. Once you pick a person from the list, it 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 sales person; they should only have the option to select it.

Once you select the sales person, now you are ready for assigning the Area that he 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 revoke the assigned area by selecting the area from the right and move it to left list box using the button <<. Support multiple selections on both sides of the list box.

The last stuff is, place the list box that all the products that need to be promoted by the sales person on his assigned area. By default USB Drive item should be selected when the form is displayed. There should be 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, last two items in the Check box is not editable. Just do this for me. Once you have finished, I will move it to a more experienced developer who will link your initial design with the database.

3. Let us start with Form design

Mr. Ax came out of the meeting thinking, "I am just having 6 months of experience! This guy is asking me do this and that. OK, If I struck up C# Corner's forum is there to help me".

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 Combo box

  1. Dropdownstyle property is set to DropDownList. This is to prevent editing of the name without picking the one provided by the combo box. Play around other types; experience the difference.

  2. Next, the sales person names are entered in the combo box using the Items property. Mr. Ax is aware that the other team is going to populate this combo box from database. So he does not need to worry about loading the combo box at runtime.

  3. Name property set to cmbSalesPerson.

 Label below the Combobox

  • Name property changed to lblDisplay.

VisitArea ListBox

  1. Name property is set to lstArea

  2. Area names are added using Items property

  3. Selection mode is set to MultiExtended. You 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. All the items in between are also selected.
    • Hold the left mouse button on the item and drag the mouse. All the items visited by the mouse pointer get selected.
       
  4. Sort property is set to true. This is to sort the list box. Useful when we move the items. This fixes the items relative position.

Button between Two Lists

  • Name property set to btnAssignbtnRevoke

Assigned ListBox

  • Name property is set to lstAssigned

  • Sorted property is set to true

  • Selection mode is set to MultiSimple. Now both the list boxes are supporting multi-selection. The difference is how the multi-selection is performed. Here, when you click the item it will go the opposite state. That is Selected â€" not selected or the reverse way.

Checked List box control [It is not a ListBox control. It is checked list box control]

  • Name property is set to lstPromote_products

  • CheckOnClick property is set to true. When it is true, clicking an item will select it and also changes the checked state of the item

  • Products are entered into the list using items property.

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

  • Name property set to chkRestricted

  • Appearance property is set to Button

  • 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 checked list box. 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. Sales person Combo box

When we change the item in the combo box, SelectedIndexChanged event is fired.  I hope you know how to get the event procedure. The lblDisplay label is set 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 in Action

The click event handler of the assign button will move all the selected items from the left listbox to the right listbox. First we retrieve the selected using the foreach loop, and then inside loop we do ask to add the item to assigned list box. Remember both the list box has the sorted property set to true.

Next, the total item selected in the Area list box is calculated. Then using a for loop the first item in the selected list collection is removed. Below is the code:

//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]);
}

Some of you may have two questions now. 1) Why the SelectedItems collection is always referred with index 0? 2) Why cannot I remove the item in the foreach itself?

For the first question, you 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, Simple, ForEach does not allow you to modify the collection in which it operates on. If need to know, Read this and debug by changing the underlying collection.

7. Revoke button in Action

Reverse of the Previous one. I hope no explanation is required.

8. Toggle button [Check box]

When we change the check states 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 last two Checklist Entry

When we place a check mark or remove it from the item, an event called ItemCheck is raised. Also the argument ItemCheckEventArgs passed to this event handler will have NewValue and CurrentValue as properties. For example if you click an item that is already in a checked state, then, NewValue is UnChecked and Current Value is Checked. OK?

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. 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;

}

Note: The attached solution is in VS2005. If you have latest version, Say "Yes" to the Conversion dialog.

COMMENT USING

Trending up