ListBox (lsb)

ListBox - Allows the user to select an item from a list of items.

Both the ComboBox and ListBox controls are derived from the ListControl class
The listindex property in a listbox control has been replaced with the "selectedindex" property.


Examples


Adding Items

listBox1.ClearSelected(); 
listBox1.BeginUpdate();
listBox1.Items.Add("Item 1");
listBox1.Items.Add("Item 3");
listBox1.Items.Add("Item 4");
listBox1.Items.Add("Item 5");
listBox1.Items.Add("Item 6");
listBox1.Items.Insert(1, "Item 2");
listBox1.EndUpdate();

Single Selection

Gets or sets the selected item.

myListBox.SelectedIndex = 1; 

Returns the string of the currently selected item.

string sItem = this.myListBox.SelectedItem.ToString(); 
System.Windows.Forms.MessageBox.Show(sItem);

For all the items in the listbox

foreach (string sItem in this.myListBox.Items) 
{
    System.Windows.Forms.MessageBox.Show(sItem);
}

Alternatively

for (int iItem = 0; iItem < this.myListBox.Items.Count; iItem++) 
{
    string sItem = this.myListBox.Items[iItem]).ToString();
    System.Windows.Forms.MessageBox.Show(sItem);
}

Multiple Selection

Selecting and unselecting multiple items.
This will not work unless the tab is currently selected (i.e. the listbox is visible)
You can use SelectedIndex instead for a single selection

listBox1.SetSelected(1, true); 
listBox1.SelectedIndex = 1;

Test if the last item in the list is selected

bool bIsSelected = this.listBox1.GetSelected(this.listBox1.Items.Count - 1); 
System.Windows.Forms.MessageBox.Show(bIsSelected.ToString());

For all the items that are currently selected.

foreach (string sItem in this.listBox1.SelectedItems) 
{
     System.Windows.Forms.MessageBox.Show(sItem);
}

Convert Items to an IList<string>

You must include Using System.Linq;

System.Collections.Generic.List<string> myCollection; 
myCollection = (this.listBox1.Items).Cast<string>().ToList();
System.Windows.Forms.MessageBox.Show(myCollection[2]);

Restrict ListBox Selection

    public partial class MyForm : Form 
    {
        private int[] aSelectedIndexes = new int[5];

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.listBox1.ClearSelected();
            this.listBox1.BeginUpdate();
            this.listBox1.Items.Add("Item 1");
            this.listBox1.Items.Add("Item 3");
            this.listBox1.Items.Add("Item 4");
            this.listBox1.Items.Add("Item 5");
            this.listBox1.Items.Add("Item 6");
            this.listBox1.Items.Insert(1, "Item 2");
            this.listBox1.EndUpdate();

            this.listBox1.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool bfound;
            int iSelectedIndex;

            if (this.listBox1.SelectedItems.Count < 5)
            {
                for (int iselectedcount = 0; iselectedcount < this.listBox1.SelectedIndices.Count; iselectedcount++)
                {
                    aSelectedIndexes[iselectedcount] = this.listBox1.SelectedIndices[iselectedcount];
                }
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("You are only allowed to select 4 items");

                for (int iselectedcount = 0; iselectedcount < this.listBox1.SelectedIndices.Count; iselectedcount++)
                {
                    bfound = false;
                    iSelectedIndex = this.listBox1.SelectedIndices[iselectedcount];

                    for (int iarraycount = 0; iarraycount < aSelectedIndexes.GetUpperBound(0); iarraycount++)
                    {
                        if (aSelectedIndexes[iarraycount] == iSelectedIndex)
                        {
                            bfound = true;
                        }
                    }

                    if (bfound == false)
                    {
                        this.listBox1.SetSelected(iSelectedIndex, false);
                        return;
                    }
                }
            }
}

Properties

AllowSelection Overridden. Gets a value indicating whether the ListBox currently enables selection of list items.
BackColorOverridden.
BorderStyleGets or sets the type of border that is drawn around the ListBox.
ColumnWidthGets or sets the width of columns in a multicolumn ListBox.
CustomTabOffsets Gets the width of the tabs between the items in the ListBox.
DataSourceGets or sets the data source for this ListControl. (Inherited from ListControl.)
DisplayMemberGets or sets the property to display for this ListControl. (Inherited from ListControl.)
DrawModeGets or sets the drawing mode for the control.
FilterItemOnProperty Overloaded. Returns the current value of the ListControl item, if the item is a property of an instance of the ListControl class. (Inherited from ListControl.)
FormatString Gets or sets the format-specifier characters that indicate how a value is to be displayed. (Inherited from ListControl.)
FormattingEnabled Gets or sets a value indicating whether formatting is applied to the DisplayMember property of the ListControl. (Inherited from ListControl.)
ForeColorOverridden.
GetScaledBounds Overridden. Retrieves the bounds within which the ListBox is scaled
HorizontalExtentGets or sets the width by which the horizontal scroll bar of a ListBox can scroll.
HorizontalScrollbarGets or sets a value indicating whether a horizontal scroll bar is displayed in the control.
IntegralHeightGets or sets a value indicating whether the control should resize to avoid showing partial items.
ItemHeightGets or sets the height of an item in the ListBox.
ItemsGets the items of the ListBox.
MultiColumnGets or sets a value indicating whether the ListBox supports multiple columns.
PreferredHeightGets the combined height of all items in the ListBox.
ScrollAlwaysVisibleGets or sets a value indicating whether the vertical scroll bar is shown at all times.
SelectedValue Gets or sets the value of the member property specified by the ValueMember property. (Inherited from ListControl.)
SelectionModeSpecifies the selection behaviour of a list box. MultiExtended, MultiSimple, One, None. Gets or sets the method in which items are selected in the ListBox.
SortedGets or sets a value indicating whether the items in the ListBox are sorted alphabetically.
Text Overridden. Gets or searches for the text of the currently selected item in the ListBox.
TopIndex Gets or sets the index of the first visible item in the ListBox.
UseTabStopsGets or sets a value indicating whether the ListBox can recognize and expand tab characters when drawing its strings.
ValueMemberGets or sets the property to use as the actual value for the items in the ListControl. (Inherited from ListControl.)

Methods

BeginUpdateMaintains performance while items are added to the ListBox one at a time by preventing the control from drawing until the EndUpdate method is called.
ClearSelectedUnselects all items in the ListBox.
DefaultItemHeightSpecifies the default item height for an owner-drawn listbox.
EndUpdateResumes painting the ListBox control after painting is suspended by the BeginUpdate method.
FindStringFinds the first item in the ListBox that starts with the specified string
FindStringExactFinds the first item in the ListBox that matches the specified string exactly.
GetItemHeight Returns the text representation of the specified item. (Inherited from ListControl.)
GetItemRectangle Returns the bounding rectangle for an item in the ListBox.
IndexFromPoint Overloaded. Returns the zero-based index of the item at the specified coordinates.
RefreshOverridden. Forces the control to invalidate its client area and immediately redraw itself and any child controls.
RefreshItem Overridden. Refreshes the item contained at the specified index.
RefreshItems Overridden. Refreshes all ListBox items and retrieves new strings for them.
Sort Sorts the items in the ListBox.
ToString Overridden. Returns a string representation of the ListBox.

Methods - Single Selection

SelectedIndexGets or sets the zero-based index of the currently selected item in the listbox. Nothing is returned if no element is currently selected. Overridden. Gets or sets the zero-based index of the currently selected item in a ListBox. This is the first selected item when you have multiple selection (SelectionMode = MultiSimple)
SelectedItemGets or sets the currently selected item in a the listbox.

Methods - Multiple Selection

GetSelectedDetermines if a particular zero-based item is currently selected.
SelectedIndexGets the zero-based index of the first selected item in the listbox.
SelectedItemGets the first selected item in the listbox. Gets or sets the currently selected item in the ListBox.
SelectedIndicesRepresents a collection of all the index positions of all the selected items. Read Only. Gets a collection that contains the zero-based indexes of all currently selected items in the ListBox.
SelectedItemsRepresents a collection of all the selected items. Read Only.
SetSelectedSelects or clears the selection for a particular zero-based item.

Events

MeasureItem Occurs when an owner-drawn ListBox is created and the sizes of the list items are determined.
MouseClick Occurs when the user clicks the ListBox control with the mouse pointer.
SelectedIndexChanged Occurs when the SelectedIndex property has changed. Fires for both single, multiple and extended selections. If using extended selection this fires after they are all selected.
SelectedValueChanged Occurs when the SelectedValue property changes. (Inherited from ListControl.)
ValueMemberChanged Occurs when the ValueMember property changes. (Inherited from ListControl.)

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext