4 out of 5 rated this helpful - Rate this topic

ListBox Class

Represents a Windows control to display a list of items.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)
[ComVisibleAttribute(true)]
[DefaultBindingPropertyAttribute("SelectedValue")]
[ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)]
public class ListBox : ListControl

The ListBox type exposes the following members.

  Name Description
Public method ListBox Initializes a new instance of the ListBox class.
Top
  Name Description
Public property AccessibilityObject Gets the AccessibleObject assigned to the control. (Inherited from Control.)
Public property AccessibleDefaultActionDescription Gets or sets the default action description of the control for use by accessibility client applications. (Inherited from Control.)
Public property AccessibleDescription Gets or sets the description of the control used by accessibility client applications. (Inherited from Control.)
Public property AccessibleName Gets or sets the name of the control used by accessibility client applications. (Inherited from Control.)
Public property AccessibleRole Gets or sets the accessible role of the control (Inherited from Control.)
Public property AllowDrop Gets or sets a value indicating whether the control can accept data that the user drags onto it. (Inherited from Control.)
Protected property AllowSelection Gets a value indicating whether the ListBox currently enables selection of list items. (Overrides ListControl.AllowSelection.)
Public property Anchor Gets or sets the edges of the container to which a control is bound and determines how a control is resized with its parent. (Inherited from Control.)
Public property AutoScrollOffset Gets or sets where this control is scrolled to in ScrollControlIntoView. (Inherited from Control.)
Public property AutoSize Infrastructure. This property is not relevant for this class. (Inherited from Control.)
Public property BackColor Gets or sets the background color for the control. (Overrides Control.BackColor.)
Public property BackgroundImage Infrastructure. This property is not relevant to this class. (Overrides Control.BackgroundImage.)
Public property BackgroundImageLayout Infrastructure. Gets or sets the background image layout for a ListBox as defined in the ImageLayout enumeration. (Overrides Control.BackgroundImageLayout.)
Public property BindingContext Gets or sets the BindingContext for the control. (Inherited from Control.)
Public property BorderStyle Gets or sets the type of border that is drawn around the ListBox.
Public property Bottom Gets the distance, in pixels, between the bottom edge of the control and the top edge of its container's client area. (Inherited from Control.)
Public property Bounds Gets or sets the size and location of the control including its nonclient elements, in pixels, relative to the parent control. (Inherited from Control.)
Protected property CanEnableIme Gets a value indicating whether the ImeMode property can be set to an active value, to enable IME support. (Inherited from Control.)
Public property CanFocus Gets a value indicating whether the control can receive focus. (Inherited from Control.)
Protected property CanRaiseEvents Determines if events can be raised on the control. (Inherited from Control.)
Public property CanSelect Gets a value indicating whether the control can be selected. (Inherited from Control.)
Public property Capture Gets or sets a value indicating whether the control has captured the mouse. (Inherited from Control.)
Public property CausesValidation Gets or sets a value indicating whether the control causes validation to be performed on any controls that require validation when it receives focus. (Inherited from Control.)
Public property ClientRectangle Gets the rectangle that represents the client area of the control. (Inherited from Control.)
Public property ClientSize Gets or sets the height and width of the client area of the control. (Inherited from Control.)
Public property ColumnWidth Gets or sets the width of columns in a multicolumn ListBox.
Public property CompanyName Gets the name of the company or creator of the application containing the control. (Inherited from Control.)
Public property Container Gets the IContainer that contains the Component. (Inherited from Component.)
Public property ContainsFocus Gets a value indicating whether the control, or one of its child controls, currently has the input focus. (Inherited from Control.)
Public property ContextMenu Gets or sets the shortcut menu associated with the control. (Inherited from Control.)
Public property ContextMenuStrip Gets or sets the ContextMenuStrip associated with this control. (Inherited from Control.)
Public property Controls Gets the collection of controls contained within the control. (Inherited from Control.)
Public property Created Gets a value indicating whether the control has been created. (Inherited from Control.)
Protected property CreateParams Gets the required creation parameters when the control handle is created. (Overrides Control.CreateParams.)
Public property Cursor Gets or sets the cursor that is displayed when the mouse pointer is over the control. (Inherited from Control.)
Public property CustomTabOffsets Gets the width of the tabs between the items in the ListBox.
Public property DataBindings Gets the data bindings for the control. (Inherited from Control.)
Protected property DataManager Gets the CurrencyManager associated with this control. (Inherited from ListControl.)
Public property DataSource Gets or sets the data source for this ListControl. (Inherited from ListControl.)
Protected property DefaultCursor Gets or sets the default cursor for the control. (Inherited from Control.)
Protected property DefaultImeMode Gets the default Input Method Editor (IME) mode supported by the control. (Inherited from Control.)
Protected property DefaultMargin Gets the space, in pixels, that is specified by default between controls. (Inherited from Control.)
Protected property DefaultMaximumSize Gets the length and height, in pixels, that is specified as the default maximum size of a control. (Inherited from Control.)
Protected property DefaultMinimumSize Gets the length and height, in pixels, that is specified as the default minimum size of a control. (Inherited from Control.)
Protected property DefaultPadding Gets the internal spacing, in pixels, of the contents of a control. (Inherited from Control.)
Protected property DefaultSize Gets the default size of the control. (Overrides Control.DefaultSize.)
Protected property DesignMode Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Public property DisplayMember Gets or sets the property to display for this ListControl. (Inherited from ListControl.)
Public property DisplayRectangle Gets the rectangle that represents the display area of the control. (Inherited from Control.)
Public property Disposing Gets a value indicating whether the base Control class is in the process of disposing. (Inherited from Control.)
Public property Dock Gets or sets which control borders are docked to its parent control and determines how a control is resized with its parent. (Inherited from Control.)
Protected property DoubleBuffered Gets or sets a value indicating whether this control should redraw its surface using a secondary buffer to reduce or prevent flicker. (Inherited from Control.)
Public property DrawMode Gets or sets the drawing mode for the control.
Public property Enabled Gets or sets a value indicating whether the control can respond to user interaction. (Inherited from Control.)
Protected property Events Gets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public property Focused Gets a value indicating whether the control has input focus. (Inherited from Control.)
Public property Font Gets or sets the font of the text displayed by the control. (Overrides Control.Font.)
Protected property FontHeight Gets or sets the height of the font of the control. (Inherited from Control.)
Public property ForeColor Gets or sets the foreground color of the control. (Overrides Control.ForeColor.)
Public property FormatInfo Gets or sets the IFormatProvider that provides custom formatting behavior. (Inherited from ListControl.)
Public property FormatString Gets or sets the format-specifier characters that indicate how a value is to be displayed. (Inherited from ListControl.)
Public property FormattingEnabled Gets or sets a value indicating whether formatting is applied to the DisplayMember property of the ListControl. (Inherited from ListControl.)
Public property Handle Gets the window handle that the control is bound to. (Inherited from Control.)
Public property HasChildren Gets a value indicating whether the control contains one or more child controls. (Inherited from Control.)
Public property Height Gets or sets the height of the control. (Inherited from Control.)
Public property HorizontalExtent Gets or sets the width by which the horizontal scroll bar of a ListBox can scroll.
Public property HorizontalScrollbar Gets or sets a value indicating whether a horizontal scroll bar is displayed in the control.
Public property ImeMode Gets or sets the Input Method Editor (IME) mode of the control. (Inherited from Control.)
Protected property ImeModeBase Gets or sets the IME mode of a control. (Inherited from Control.)
Public property IntegralHeight Gets or sets a value indicating whether the control should resize to avoid showing partial items.
Public property InvokeRequired Gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on. (Inherited from Control.)
Public property IsAccessible Gets or sets a value indicating whether the control is visible to accessibility applications. (Inherited from Control.)
Public property IsDisposed Gets a value indicating whether the control has been disposed of. (Inherited from Control.)
Public property IsHandleCreated Gets a value indicating whether the control has a handle associated with it. (Inherited from Control.)
Public property IsMirrored Gets a value indicating whether the control is mirrored. (Inherited from Control.)
Public property ItemHeight Gets or sets the height of an item in the ListBox.
Public property Items Gets the items of the ListBox.
Public property LayoutEngine Gets a cached instance of the control's layout engine. (Inherited from Control.)
Public property Left Gets or sets the distance, in pixels, between the left edge of the control and the left edge of its container's client area. (Inherited from Control.)
Public property Location Gets or sets the coordinates of the upper-left corner of the control relative to the upper-left corner of its container. (Inherited from Control.)
Public property Margin Gets or sets the space between controls. (Inherited from Control.)
Public property MaximumSize Gets or sets the size that is the upper limit that GetPreferredSize can specify. (Inherited from Control.)
Public property MinimumSize Gets or sets the size that is the lower limit that GetPreferredSize can specify. (Inherited from Control.)
Public property MultiColumn Gets or sets a value indicating whether the ListBox supports multiple columns.
Public property Name Gets or sets the name of the control. (Inherited from Control.)
Public property Padding Infrastructure. This property is not relevant to this class.
Public property Parent Gets or sets the parent container of the control. (Inherited from Control.)
Public property PreferredHeight Gets the combined height of all items in the ListBox.
Public property PreferredSize Gets the size of a rectangular area into which the control can fit. (Inherited from Control.)
Public property ProductName Gets the product name of the assembly containing the control. (Inherited from Control.)
Public property ProductVersion Gets the version of the assembly containing the control. (Inherited from Control.)
Public property RecreatingHandle Gets a value indicating whether the control is currently re-creating its handle. (Inherited from Control.)
Public property Region Gets or sets the window region associated with the control. (Inherited from Control.)
Protected property RenderRightToLeft Obsolete. This property is now obsolete. (Inherited from Control.)
Protected property ResizeRedraw Gets or sets a value indicating whether the control redraws itself when resized. (Inherited from Control.)
Public property Right Gets the distance, in pixels, between the right edge of the control and the left edge of its container's client area. (Inherited from Control.)
Public property RightToLeft Gets or sets a value indicating whether text displayed by the control is displayed from right to left. (Overrides Control.RightToLeft.)
Protected property ScaleChildren Gets a value that determines the scaling of child controls. (Inherited from Control.)
Public property ScrollAlwaysVisible Gets or sets a value indicating whether the vertical scroll bar is shown at all times.
Public property SelectedIndex Gets or sets the zero-based index of the currently selected item in a ListBox. (Overrides ListControl.SelectedIndex.)
Public property SelectedIndices Gets a collection that contains the zero-based indexes of all currently selected items in the ListBox.
Public property SelectedItem Gets or sets the currently selected item in the ListBox.
Public property SelectedItems Gets a collection containing the currently selected items in the ListBox.
Public property SelectedValue Gets or sets the value of the member property specified by the ValueMember property. (Inherited from ListControl.)
Public property SelectionMode Gets or sets the method in which items are selected in the ListBox.
Protected property ShowFocusCues Gets a value indicating whether the control should display focus rectangles. (Inherited from Control.)
Protected property ShowKeyboardCues Gets a value indicating whether the user interface is in the appropriate state to show or hide keyboard accelerators. (Inherited from Control.)
Public property Site Gets or sets the site of the control. (Inherited from Control.)
Public property Size Gets or sets the height and width of the control. (Inherited from Control.)
Public property Sorted Gets or sets a value indicating whether the items in the ListBox are sorted alphabetically.
Public property TabIndex Gets or sets the tab order of the control within its container. (Inherited from Control.)
Public property TabStop Gets or sets a value indicating whether the user can give the focus to this control using the TAB key. (Inherited from Control.)
Public property Tag Gets or sets the object that contains data about the control. (Inherited from Control.)
Public property Text Gets or searches for the text of the currently selected item in the ListBox. (Overrides Control.Text.)
Public property Top Gets or sets the distance, in pixels, between the top edge of the control and the top edge of its container's client area. (Inherited from Control.)
Public property TopIndex Gets or sets the index of the first visible item in the ListBox.
Public property TopLevelControl Gets the parent control that is not parented by another Windows Forms control. Typically, this is the outermost Form that the control is contained in. (Inherited from Control.)
Public property UseCustomTabOffsets Gets or sets a value indicating whether the ListBox recognizes and expands tab characters when it draws its strings by using the CustomTabOffsets integer array.
Public property UseTabStops Gets or sets a value indicating whether the ListBox can recognize and expand tab characters when drawing its strings.
Public property UseWaitCursor Gets or sets a value indicating whether to use the wait cursor for the current control and all child controls. (Inherited from Control.)
Public property ValueMember Gets or sets the property to use as the actual value for the items in the ListControl. (Inherited from ListControl.)
Public property Visible Gets or sets a value indicating whether the control and all its child controls are displayed. (Inherited from Control.)
Public property Width Gets or sets the width of the control. (Inherited from Control.)
Public property WindowTarget Infrastructure. This property is not relevant for this class. (Inherited from Control.)
Top
  Name Description
Protected method AccessibilityNotifyClients(AccessibleEvents, Int32) Notifies the accessibility client applications of the specified AccessibleEvents for the specified child control. (Inherited from Control.)
Protected method AccessibilityNotifyClients(AccessibleEvents, Int32, Int32) Notifies the accessibility client applications of the specified AccessibleEvents for the specified child control . (Inherited from Control.)
Protected method AddItemsCore Obsolete. This member is obsolete, and there is no replacement.
Public method BeginInvoke(Delegate) Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on. (Inherited from Control.)
Public method BeginInvoke(Delegate, Object[]) Executes the specified delegate asynchronously with the specified arguments, on the thread that the control's underlying handle was created on. (Inherited from Control.)
Public method BeginUpdate Maintains performance while items are added to the ListBox one at a time by preventing the control from drawing until the EndUpdate method is called.
Public method BringToFront Brings the control to the front of the z-order. (Inherited from Control.)
Public method ClearSelected Unselects all items in the ListBox.
Public method Contains Retrieves a value indicating whether the specified control is a child of the control. (Inherited from Control.)
Protected method CreateAccessibilityInstance Creates a new accessibility object for the control. (Inherited from Control.)
Public method CreateControl Forces the creation of the visible control, including the creation of the handle and any visible child controls. (Inherited from Control.)
Protected method CreateControlsInstance Creates a new instance of the control collection for the control. (Inherited from Control.)
Public method CreateGraphics Creates the Graphics for the control. (Inherited from Control.)
Protected method CreateHandle Creates a handle for the control. (Inherited from Control.)
Protected method CreateItemCollection Creates a new instance of the item collection.
Public method CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Protected method DefWndProc Sends the specified message to the default window procedure. (Inherited from Control.)
Protected method DestroyHandle Destroys the handle associated with the control. (Inherited from Control.)
Public method Dispose() Releases all resources used by the Component. (Inherited from Component.)
Protected method Dispose(Boolean) Releases the unmanaged resources used by the Control and its child controls and optionally releases the managed resources. (Inherited from Control.)
Public method DoDragDrop Begins a drag-and-drop operation. (Inherited from Control.)
Public method DrawToBitmap Supports rendering to the specified bitmap. (Inherited from Control.)
Public method EndInvoke Retrieves the return value of the asynchronous operation represented by the IAsyncResult passed. (Inherited from Control.)
Public method EndUpdate Resumes painting the ListBox control after painting is suspended by the BeginUpdate method.
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method FilterItemOnProperty(Object) Retrieves the current value of the ListControl item, if it is a property of an object, given the item. (Inherited from ListControl.)
Protected method FilterItemOnProperty(Object, String) Returns the current value of the ListControl item, if it is a property of an object given the item and the property name. (Inherited from ListControl.)
Protected method Finalize Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public method FindForm Retrieves the form that the control is on. (Inherited from Control.)
Public method FindString(String) Finds the first item in the ListBox that starts with the specified string.
Public method FindString(String, Int32) Finds the first item in the ListBox that starts with the specified string. The search starts at a specific starting index.
Public method FindStringExact(String) Finds the first item in the ListBox that exactly matches the specified string.
Public method FindStringExact(String, Int32) Finds the first item in the ListBox that exactly matches the specified string. The search starts at a specific starting index.
Public method Focus Sets input focus to the control. (Inherited from Control.)
Protected method GetAccessibilityObjectById Retrieves the specified AccessibleObject. (Inherited from Control.)
Protected method GetAutoSizeMode Retrieves a value indicating how a control will behave when its AutoSize property is enabled. (Inherited from Control.)
Public method GetChildAtPoint(Point) Retrieves the child control that is located at the specified coordinates. (Inherited from Control.)
Public method GetChildAtPoint(Point, GetChildAtPointSkip) Retrieves the child control that is located at the specified coordinates, specifying whether to ignore child controls of a certain type. (Inherited from Control.)
Public method GetContainerControl Returns the next ContainerControl up the control's chain of parent controls. (Inherited from Control.)
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetItemHeight Returns the height of an item in the ListBox.
Public method GetItemRectangle Returns the bounding rectangle for an item in the ListBox.
Public method GetItemText Returns the text representation of the specified item. (Inherited from ListControl.)
Public method GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public method GetNextControl Retrieves the next control forward or back in the tab order of child controls. (Inherited from Control.)
Public method GetPreferredSize Retrieves the size of a rectangular area into which a control can be fitted. (Inherited from Control.)
Protected method GetScaledBounds Retrieves the bounds within which the ListBox is scaled. (Overrides Control.GetScaledBounds(Rectangle, SizeF, BoundsSpecified).)
Public method GetSelected Returns a value indicating whether the specified item is selected.
Protected method GetService Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Protected method GetStyle Retrieves the value of the specified control style bit for the control. (Inherited from Control.)
Protected method GetTopLevel Determines if the control is a top-level control. (Inherited from Control.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method Hide Conceals the control from the user. (Inherited from Control.)
Public method IndexFromPoint(Point) Returns the zero-based index of the item at the specified coordinates.
Public method IndexFromPoint(Int32, Int32) Returns the zero-based index of the item at the specified coordinates.
Public method InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method InitLayout Called after the control has been added to another container. (Inherited from Control.)
Public method Invalidate() Invalidates the entire surface of the control and causes the control to be redrawn. (Inherited from Control.)
Public method Invalidate(Boolean) Invalidates a specific region of the control and causes a paint message to be sent to the control. Optionally, invalidates the child controls assigned to the control. (Inherited from Control.)
Public method Invalidate(Rectangle) Invalidates the specified region of the control (adds it to the control's update region, which is the area that will be repainted at the next paint operation), and causes a paint message to be sent to the control. (Inherited from Control.)
Public method Invalidate(Region) Invalidates the specified region of the control (adds it to the control's update region, which is the area that will be repainted at the next paint operation), and causes a paint message to be sent to the control. (Inherited from Control.)
Public method Invalidate(Rectangle, Boolean) Invalidates the specified region of the control (adds it to the control's update region, which is the area that will be repainted at the next paint operation), and causes a paint message to be sent to the control. Optionally, invalidates the child controls assigned to the control. (Inherited from Control.)
Public method Invalidate(Region, Boolean) Invalidates the specified region of the control (adds it to the control's update region, which is the area that will be repainted at the next paint operation), and causes a paint message to be sent to the control. Optionally, invalidates the child controls assigned to the control. (Inherited from Control.)
Public method Invoke(Delegate) Executes the specified delegate on the thread that owns the control's underlying window handle. (Inherited from Control.)
Public method Invoke(Delegate, Object[]) Executes the specified delegate, on the thread that owns the control's underlying window handle, with the specified list of arguments. (Inherited from Control.)
Protected method InvokeGotFocus Raises the GotFocus event for the specified control. (Inherited from Control.)
Protected method InvokeLostFocus Raises the LostFocus event for the specified control. (Inherited from Control.)
Protected method InvokeOnClick Raises the Click event for the specified control. (Inherited from Control.)
Protected method InvokePaint Raises the Paint event for the specified control. (Inherited from Control.)
Protected method InvokePaintBackground Raises the PaintBackground event for the specified control. (Inherited from Control.)
Protected method IsInputChar Determines if a character is an input character that the control recognizes. (Inherited from Control.)
Protected method IsInputKey Handles special input keys, such as PAGE UP, PAGE DOWN, HOME, END, and so on. (Inherited from ListControl.)
Protected method MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected method NotifyInvalidate Infrastructure. Raises the Invalidated event with a specified region of the control to invalidate. (Inherited from Control.)
Protected method OnAutoSizeChanged Raises the AutoSizeChanged event. (Inherited from Control.)
Protected method OnBackColorChanged Raises the BackColorChanged event. (Inherited from Control.)
Protected method OnBackgroundImageChanged Raises the BackgroundImageChanged event. (Inherited from Control.)
Protected method OnBackgroundImageLayoutChanged Raises the BackgroundImageLayoutChanged event. (Inherited from Control.)
Protected method OnBindingContextChanged Raises the BindingContextChanged event. (Inherited from ListControl.)
Protected method OnCausesValidationChanged Raises the CausesValidationChanged event. (Inherited from Control.)
Protected method OnChangeUICues Raises the ChangeUICues event. (Overrides Control.OnChangeUICues(UICuesEventArgs).)
Protected method OnClick Raises the Click event. (Inherited from Control.)
Protected method OnClientSizeChanged Raises the ClientSizeChanged event. (Inherited from Control.)
Protected method OnContextMenuChanged Raises the ContextMenuChanged event. (Inherited from Control.)
Protected method OnContextMenuStripChanged Raises the ContextMenuStripChanged event. (Inherited from Control.)
Protected method OnControlAdded Raises the ControlAdded event. (Inherited from Control.)
Protected method OnControlRemoved Raises the ControlRemoved event. (Inherited from Control.)
Protected method OnCreateControl Raises the CreateControl method. (Inherited from Control.)
Protected method OnCursorChanged Raises the CursorChanged event. (Inherited from Control.)
Protected method OnDataSourceChanged Raises the DataSourceChanged event. (Overrides ListControl.OnDataSourceChanged(EventArgs).)
Protected method OnDisplayMemberChanged Raises the DisplayMemberChanged event. (Overrides ListControl.OnDisplayMemberChanged(EventArgs).)
Protected method OnDockChanged Raises the DockChanged event. (Inherited from Control.)
Protected method OnDoubleClick Raises the DoubleClick event. (Inherited from Control.)
Protected method OnDragDrop Raises the DragDrop event. (Inherited from Control.)
Protected method OnDragEnter Raises the DragEnter event. (Inherited from Control.)
Protected method OnDragLeave Raises the DragLeave event. (Inherited from Control.)
Protected method OnDragOver Raises the DragOver event. (Inherited from Control.)
Protected method OnDrawItem Raises the DrawItem event.
Protected method OnEnabledChanged Raises the EnabledChanged event. (Inherited from Control.)
Protected method OnEnter Raises the Enter event. (Inherited from Control.)
Protected method OnFontChanged Raises the FontChanged event. (Overrides Control.OnFontChanged(EventArgs).)
Protected method OnForeColorChanged Raises the ForeColorChanged event. (Inherited from Control.)
Protected method OnFormat Raises the Format event. (Inherited from ListControl.)
Protected method OnFormatInfoChanged Raises the FormatInfoChanged event. (Inherited from ListControl.)
Protected method OnFormatStringChanged Raises the FormatStringChanged event. (Inherited from ListControl.)
Protected method OnFormattingEnabledChanged Raises the FormattingEnabledChanged event. (Inherited from ListControl.)
Protected method OnGiveFeedback Raises the GiveFeedback event. (Inherited from Control.)
Protected method OnGotFocus Raises the GotFocus event. (Inherited from Control.)
Protected method OnHandleCreated Specifies when the window handle has been created so that column width and other characteristics can be set. Inheriting classes should call base.OnHandleCreated. (Overrides Control.OnHandleCreated(EventArgs).)
Protected method OnHandleDestroyed Overridden to be sure that items are set up and cleared out correctly. Inheriting controls should call base.OnHandleDestroyed. (Overrides Control.OnHandleDestroyed(EventArgs).)
Protected method OnHelpRequested Raises the HelpRequested event. (Inherited from Control.)
Protected method OnImeModeChanged Raises the ImeModeChanged event. (Inherited from Control.)
Protected method OnInvalidated Raises the Invalidated event. (Inherited from Control.)
Protected method OnKeyDown Raises the KeyDown event. (Inherited from Control.)
Protected method OnKeyPress Raises the KeyPress event. (Inherited from Control.)
Protected method OnKeyUp Raises the KeyUp event. (Inherited from Control.)
Protected method OnLayout Raises the Layout event. (Inherited from Control.)
Protected method OnLeave Raises the Leave event. (Inherited from Control.)
Protected method OnLocationChanged Raises the LocationChanged event. (Inherited from Control.)
Protected method OnLostFocus Raises the LostFocus event. (Inherited from Control.)
Protected method OnMarginChanged Raises the MarginChanged event. (Inherited from Control.)
Protected method OnMeasureItem Raises the MeasureItem event.
Protected method OnMouseCaptureChanged Raises the MouseCaptureChanged event. (Inherited from Control.)
Protected method OnMouseClick Raises the MouseClick event. (Inherited from Control.)
Protected method OnMouseDoubleClick Raises the MouseDoubleClick event. (Inherited from Control.)
Protected method OnMouseDown Raises the MouseDown event. (Inherited from Control.)
Protected method OnMouseEnter Raises the MouseEnter event. (Inherited from Control.)
Protected method OnMouseHover Raises the MouseHover event. (Inherited from Control.)
Protected method OnMouseLeave Raises the MouseLeave event. (Inherited from Control.)
Protected method OnMouseMove Raises the MouseMove event. (Inherited from Control.)
Protected method OnMouseUp Raises the MouseUp event. (Inherited from Control.)
Protected method OnMouseWheel Raises the MouseWheel event. (Inherited from Control.)
Protected method OnMove Raises the Move event. (Inherited from Control.)
Protected method OnNotifyMessage Notifies the control of Windows messages. (Inherited from Control.)
Protected method OnPaddingChanged Raises the PaddingChanged event. (Inherited from Control.)
Protected method OnPaint Raises the Paint event. (Inherited from Control.)
Protected method OnPaintBackground Paints the background of the control. (Inherited from Control.)
Protected method OnParentBackColorChanged Raises the BackColorChanged event when the BackColor property value of the control's container changes. (Inherited from Control.)
Protected method OnParentBackgroundImageChanged Raises the BackgroundImageChanged event when the BackgroundImage property value of the control's container changes. (Inherited from Control.)
Protected method OnParentBindingContextChanged Raises the BindingContextChanged event when the BindingContext property value of the control's container changes. (Inherited from Control.)
Protected method OnParentChanged Raises the ParentChanged event. (Overrides Control.OnParentChanged(EventArgs).)
Protected method OnParentCursorChanged Raises the CursorChanged event. (Inherited from Control.)
Protected method OnParentEnabledChanged Raises the EnabledChanged event when the Enabled property value of the control's container changes. (Inherited from Control.)
Protected method OnParentFontChanged Raises the FontChanged event when the Font property value of the control's container changes. (Inherited from Control.)
Protected method OnParentForeColorChanged Raises the ForeColorChanged event when the ForeColor property value of the control's container changes. (Inherited from Control.)
Protected method OnParentRightToLeftChanged Raises the RightToLeftChanged event when the RightToLeft property value of the control's container changes. (Inherited from Control.)
Protected method OnParentVisibleChanged Raises the VisibleChanged event when the Visible property value of the control's container changes. (Inherited from Control.)
Protected method OnPreviewKeyDown Raises the PreviewKeyDown event. (Inherited from Control.)
Protected method OnPrint Raises the Paint event. (Inherited from Control.)
Protected method OnQueryContinueDrag Raises the QueryContinueDrag event. (Inherited from Control.)
Protected method OnRegionChanged Raises the RegionChanged event. (Inherited from Control.)
Protected method OnResize Raises the Resize event. (Overrides Control.OnResize(EventArgs).)
Protected method OnRightToLeftChanged Raises the RightToLeftChanged event. (Inherited from Control.)
Protected method OnSelectedIndexChanged Raises the SelectedValueChanged event. (Overrides ListControl.OnSelectedIndexChanged(EventArgs).)
Protected method OnSelectedValueChanged Raises the SelectedValueChanged event. (Overrides ListControl.OnSelectedValueChanged(EventArgs).)
Protected method OnSizeChanged Raises the SizeChanged event. (Inherited from Control.)
Protected method OnStyleChanged Raises the StyleChanged event. (Inherited from Control.)
Protected method OnSystemColorsChanged Raises the SystemColorsChanged event. (Inherited from Control.)
Protected method OnTabIndexChanged Raises the TabIndexChanged event. (Inherited from Control.)
Protected method OnTabStopChanged Raises the TabStopChanged event. (Inherited from Control.)
Protected method OnTextChanged Raises the TextChanged event. (Inherited from Control.)
Protected method OnValidated Raises the Validated event. (Inherited from Control.)
Protected method OnValidating Raises the Validating event. (Inherited from Control.)
Protected method OnValueMemberChanged Raises the ValueMemberChanged event. (Inherited from ListControl.)
Protected method OnVisibleChanged Raises the VisibleChanged event. (Inherited from Control.)
Public method PerformLayout() Forces the control to apply layout logic to all its child controls. (Inherited from Control.)
Public method PerformLayout(Control, String) Forces the control to apply layout logic to all its child controls. (Inherited from Control.)
Public method PointToClient Computes the location of the specified screen point into client coordinates. (Inherited from Control.)
Public method PointToScreen Computes the location of the specified client point into screen coordinates. (Inherited from Control.)
Public method PreProcessControlMessage Preprocesses keyboard or input messages within the message loop before they are dispatched. (Inherited from Control.)
Public method PreProcessMessage Preprocesses keyboard or input messages within the message loop before they are dispatched. (Inherited from Control.)
Protected method ProcessCmdKey Processes a command key. (Inherited from Control.)
Protected method ProcessDialogChar Processes a dialog character. (Inherited from Control.)
Protected method ProcessDialogKey Processes a dialog key. (Inherited from Control.)
Protected method ProcessKeyEventArgs Processes a key message and generates the appropriate control events. (Inherited from Control.)
Protected method ProcessKeyMessage Processes a keyboard message. (Inherited from Control.)
Protected method ProcessKeyPreview Previews a keyboard message. (Inherited from Control.)
Protected method ProcessMnemonic Processes a mnemonic character. (Inherited from Control.)
Protected method RaiseDragEvent Infrastructure. Raises the appropriate drag event. (Inherited from Control.)
Protected method RaiseKeyEvent Infrastructure. Raises the appropriate key event. (Inherited from Control.)
Protected method RaiseMouseEvent Infrastructure. Raises the appropriate mouse event. (Inherited from Control.)
Protected method RaisePaintEvent Infrastructure. Raises the appropriate paint event. (Inherited from Control.)
Protected method RecreateHandle Forces the re-creation of the handle for the control. (Inherited from Control.)
Public method RectangleToClient Computes the size and location of the specified screen rectangle in client coordinates. (Inherited from Control.)
Public method RectangleToScreen Computes the size and location of the specified client rectangle in screen coordinates. (Inherited from Control.)
Public method Refresh Forces the control to invalidate its client area and immediately redraw itself and any child controls. (Overrides Control.Refresh().)
Protected method RefreshItem Infrastructure. Refreshes the item contained at the specified index. (Overrides ListControl.RefreshItem(Int32).)
Protected method RefreshItems Refreshes all ListBox items and retrieves new strings for them. (Overrides ListControl.RefreshItems().)
Public method ResetBackColor Resets the BackColor property to its default value. (Overrides Control.ResetBackColor().)
Public method ResetBindings Causes a control bound to the BindingSource to reread all the items in the list and refresh their displayed values. (Inherited from Control.)
Public method ResetCursor Resets the Cursor property to its default value. (Inherited from Control.)
Public method ResetFont Resets the Font property to its default value. (Inherited from Control.)
Public method ResetForeColor Resets the ForeColor property to its default value. (Overrides Control.ResetForeColor().)
Public method ResetImeMode Resets the ImeMode property to its default value. (Inherited from Control.)
Protected method ResetMouseEventArgs Infrastructure. Resets the control to handle the MouseLeave event. (Inherited from Control.)
Public method ResetRightToLeft Resets the RightToLeft property to its default value. (Inherited from Control.)
Public method ResetText Resets the Text property to its default value. (Inherited from Control.)
Public method ResumeLayout() Resumes usual layout logic. (Inherited from Control.)
Public method ResumeLayout(Boolean) Resumes usual layout logic, optionally forcing an immediate layout of pending layout requests. (Inherited from Control.)
Protected method RtlTranslateAlignment(ContentAlignment) Converts the specified ContentAlignment to the appropriate ContentAlignment to support right-to-left text. (Inherited from Control.)
Protected method RtlTranslateAlignment(HorizontalAlignment) Converts the specified HorizontalAlignment to the appropriate HorizontalAlignment to support right-to-left text. (Inherited from Control.)
Protected method RtlTranslateAlignment(LeftRightAlignment) Converts the specified LeftRightAlignment to the appropriate LeftRightAlignment to support right-to-left text. (Inherited from Control.)
Protected method RtlTranslateContent Converts the specified ContentAlignment to the appropriate ContentAlignment to support right-to-left text. (Inherited from Control.)
Protected method RtlTranslateHorizontal Converts the specified HorizontalAlignment to the appropriate HorizontalAlignment to support right-to-left text. (Inherited from Control.)
Protected method RtlTranslateLeftRight Converts the specified LeftRightAlignment to the appropriate LeftRightAlignment to support right-to-left text. (Inherited from Control.)
Public method Scale(Single) Obsolete. Scales the control and any child controls. (Inherited from Control.)
Public method Scale(SizeF) Scales the control and all child controls by the specified scaling factor. (Inherited from Control.)
Public method Scale(Single, Single) Obsolete. Scales the entire control and any child controls. (Inherited from Control.)
Protected method ScaleControl Scales a control's location, size, padding and margin. (Overrides Control.ScaleControl(SizeF, BoundsSpecified).)
Protected method ScaleCore Infrastructure. This method is not relevant for this class. (Inherited from Control.)
Public method Select() Activates the control. (Inherited from Control.)
Protected method Select(Boolean, Boolean) Activates a child control. Optionally specifies the direction in the tab order to select the control from. (Inherited from Control.)
Public method SelectNextControl Activates the next control. (Inherited from Control.)
Public method SendToBack Sends the control to the back of the z-order. (Inherited from Control.)
Protected method SetAutoSizeMode Sets a value indicating how a control will behave when its AutoSize property is enabled. (Inherited from Control.)
Public method SetBounds(Int32, Int32, Int32, Int32) Sets the bounds of the control to the specified location and size. (Inherited from Control.)
Public method SetBounds(Int32, Int32, Int32, Int32, BoundsSpecified) Sets the specified bounds of the control to the specified location and size. (Inherited from Control.)
Protected method SetBoundsCore Infrastructure. Sets the specified bounds of the ListBox control. (Overrides Control.SetBoundsCore(Int32, Int32, Int32, Int32, BoundsSpecified).)
Protected method SetClientSizeCore Sets the size of the client area of the control. (Inherited from Control.)
Protected method SetItemCore Sets the object with the specified index in the derived class. (Overrides ListControl.SetItemCore(Int32, Object).)
Protected method SetItemsCore Clears the contents of the ListBox and adds the specified items to the control. (Overrides ListControl.SetItemsCore(IList).)
Public method SetSelected Selects or clears the selection for the specified item in a ListBox.
Protected method SetStyle Sets a specified ControlStyles flag to either true or false. (Inherited from Control.)
Protected method SetTopLevel Sets the control as the top-level control. (Inherited from Control.)
Protected method SetVisibleCore Sets the control to the specified visible state. (Inherited from Control.)
Public method Show Displays the control to the user. (Inherited from Control.)
Protected method SizeFromClientSize Determines the size of the entire control from the height and width of its client area. (Inherited from Control.)
Protected method Sort Sorts the items in the ListBox.
Public method SuspendLayout Temporarily suspends the layout logic for the control. (Inherited from Control.)
Public method ToString Infrastructure. Returns a string representation of the ListBox. (Overrides Component.ToString().)
Public method Update Causes the control to redraw the invalidated regions within its client area. (Inherited from Control.)
Protected method UpdateBounds() Updates the bounds of the control with the current size and location. (Inherited from Control.)
Protected method UpdateBounds(Int32, Int32, Int32, Int32) Updates the bounds of the control with the specified size and location. (Inherited from Control.)
Protected method UpdateBounds(Int32, Int32, Int32, Int32, Int32, Int32) Updates the bounds of the control with the specified size, location, and client size. (Inherited from Control.)
Protected method UpdateStyles Forces the assigned styles to be reapplied to the control. (Inherited from Control.)
Protected method UpdateZOrder Updates the control in its parent's z-order. (Inherited from Control.)
Protected method WmReflectCommand Infrastructure. Processes the command message the ListView control receives from the top-level window.
Protected method WndProc The list's window procedure. (Overrides Control.WndProc(Message).)
Top
  Name Description
Public event AutoSizeChanged Infrastructure. This event is not relevant for this class. (Inherited from Control.)
Public event BackColorChanged Occurs when the value of the BackColor property changes. (Inherited from Control.)
Public event BackgroundImageChanged Infrastructure. Occurs when the BackgroundImage property of the label changes.
Public event BackgroundImageLayoutChanged Infrastructure. Occurs when the BackgroundImageLayout property changes.
Public event BindingContextChanged Occurs when the value of the BindingContext property changes. (Inherited from Control.)
Public event CausesValidationChanged Occurs when the value of the CausesValidation property changes. (Inherited from Control.)
Public event ChangeUICues Occurs when the focus or keyboard user interface (UI) cues change. (Inherited from Control.)
Public event Click Infrastructure. Occurs when the ListBox control is clicked.
Public event ClientSizeChanged Occurs when the value of the ClientSize property changes. (Inherited from Control.)
Public event ContextMenuChanged Occurs when the value of the ContextMenu property changes. (Inherited from Control.)
Public event ContextMenuStripChanged Occurs when the value of the ContextMenuStrip property changes. (Inherited from Control.)
Public event ControlAdded Occurs when a new control is added to the Control.ControlCollection. (Inherited from Control.)
Public event ControlRemoved Occurs when a control is removed from the Control.ControlCollection. (Inherited from Control.)
Public event CursorChanged Occurs when the value of the Cursor property changes. (Inherited from Control.)
Public event DataSourceChanged Occurs when the DataSource changes. (Inherited from ListControl.)
Public event DisplayMemberChanged Occurs when the DisplayMember property changes. (Inherited from ListControl.)
Public event Disposed Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Public event DockChanged Occurs when the value of the Dock property changes. (Inherited from Control.)
Public event DoubleClick Occurs when the control is double-clicked. (Inherited from Control.)
Public event DragDrop Occurs when a drag-and-drop operation is completed. (Inherited from Control.)
Public event DragEnter Occurs when an object is dragged into the control's bounds. (Inherited from Control.)
Public event DragLeave Occurs when an object is dragged out of the control's bounds. (Inherited from Control.)
Public event DragOver Occurs when an object is dragged over the control's bounds. (Inherited from Control.)
Public event DrawItem Occurs when a visual aspect of an owner-drawn ListBox changes.
Public event EnabledChanged Occurs when the Enabled property value has changed. (Inherited from Control.)
Public event Enter Occurs when the control is entered. (Inherited from Control.)
Public event FontChanged Occurs when the Font property value changes. (Inherited from Control.)
Public event ForeColorChanged Occurs when the ForeColor property value changes. (Inherited from Control.)
Public event Format Occurs when the control is bound to a data value. (Inherited from ListControl.)
Public event FormatInfoChanged Occurs when the value of the FormatInfo property changes. (Inherited from ListControl.)
Public event FormatStringChanged Occurs when value of the FormatString property changes (Inherited from ListControl.)
Public event FormattingEnabledChanged Occurs when the value of the FormattingEnabled property changes. (Inherited from ListControl.)
Public event GiveFeedback Occurs during a drag operation. (Inherited from Control.)
Public event GotFocus Occurs when the control receives focus. (Inherited from Control.)
Public event HandleCreated Occurs when a handle is created for the control. (Inherited from Control.)
Public event HandleDestroyed Occurs when the control's handle is in the process of being destroyed. (Inherited from Control.)
Public event HelpRequested Occurs when the user requests help for a control. (Inherited from Control.)
Public event ImeModeChanged Occurs when the ImeMode property has changed. (Inherited from Control.)
Public event Invalidated Occurs when a control's display requires redrawing. (Inherited from Control.)
Public event KeyDown Occurs when a key is pressed while the control has focus. (Inherited from Control.)
Public event KeyPress Occurs when a key is pressed while the control has focus. (Inherited from Control.)
Public event KeyUp Occurs when a key is released while the control has focus. (Inherited from Control.)
Public event Layout Occurs when a control should reposition its child controls. (Inherited from Control.)
Public event Leave Occurs when the input focus leaves the control. (Inherited from Control.)
Public event LocationChanged Occurs when the Location property value has changed. (Inherited from Control.)
Public event LostFocus Occurs when the control loses focus. (Inherited from Control.)
Public event MarginChanged Occurs when the control's margin changes. (Inherited from Control.)
Public event MeasureItem Occurs when an owner-drawn ListBox is created and the sizes of the list items are determined.
Public event MouseCaptureChanged Occurs when the control loses mouse capture. (Inherited from Control.)
Public event MouseClick Infrastructure. Occurs when the user clicks the ListBox control with the mouse pointer.
Public event MouseDoubleClick Occurs when the control is double clicked by the mouse. (Inherited from Control.)
Public event MouseDown Occurs when the mouse pointer is over the control and a mouse button is pressed. (Inherited from Control.)
Public event MouseEnter Occurs when the mouse pointer enters the control. (Inherited from Control.)
Public event MouseHover Occurs when the mouse pointer rests on the control. (Inherited from Control.)
Public event MouseLeave Occurs when the mouse pointer leaves the control. (Inherited from Control.)
Public event MouseMove Occurs when the mouse pointer is moved over the control. (Inherited from Control.)
Public event MouseUp Occurs when the mouse pointer is over the control and a mouse button is released. (Inherited from Control.)
Public event MouseWheel Occurs when the mouse wheel moves while the control has focus. (Inherited from Control.)
Public event Move Occurs when the control is moved. (Inherited from Control.)
Public event PaddingChanged Occurs when the value of the Padding property changes.
Public event Paint Infrastructure. Occurs when the ListBox control is painted.
Public event ParentChanged Occurs when the Parent property value changes. (Inherited from Control.)
Public event PreviewKeyDown Occurs before the KeyDown event when a key is pressed while focus is on this control. (Inherited from Control.)
Public event QueryAccessibilityHelp Occurs when AccessibleObject is providing help to accessibility applications. (Inherited from Control.)
Public event QueryContinueDrag Occurs during a drag-and-drop operation and enables the drag source to determine whether the drag-and-drop operation should be canceled. (Inherited from Control.)
Public event RegionChanged Occurs when the value of the Region property changes. (Inherited from Control.)
Public event Resize Occurs when the control is resized. (Inherited from Control.)
Public event RightToLeftChanged Occurs when the RightToLeft property value changes. (Inherited from Control.)
Public event SelectedIndexChanged Occurs when the SelectedIndex property or the SelectedIndices collection has changed.
Public event SelectedValueChanged Occurs when the SelectedValue property changes. (Inherited from ListControl.)
Public event SizeChanged Occurs when the Size property value changes. (Inherited from Control.)
Public event StyleChanged Occurs when the control style changes. (Inherited from Control.)
Public event SystemColorsChanged Occurs when the system colors change. (Inherited from Control.)
Public event TabIndexChanged Occurs when the TabIndex property value changes. (Inherited from Control.)
Public event TabStopChanged Occurs when the TabStop property value changes. (Inherited from Control.)
Public event TextChanged Infrastructure. Occurs when the Text property is changed.
Public event Validated Occurs when the control is finished validating. (Inherited from Control.)
Public event Validating Occurs when the control is validating. (Inherited from Control.)
Public event ValueMemberChanged Occurs when the ValueMember property changes. (Inherited from ListControl.)
Public event VisibleChanged Occurs when the Visible property value changes. (Inherited from Control.)
Top
  Name Description
Public field Static member DefaultItemHeight Specifies the default item height for an owner-drawn ListBox.
Public field Static member NoMatches Specifies that no matches are found during a search.
Top
  Name Description
Explicit interface implemetation Private method IDropTarget.OnDragDrop Infrastructure. Raises the DragDrop event. (Inherited from Control.)
Explicit interface implemetation Private method IDropTarget.OnDragEnter Infrastructure. Raises the DragEnter event. (Inherited from Control.)
Explicit interface implemetation Private method IDropTarget.OnDragLeave Infrastructure. Raises the DragLeave event. (Inherited from Control.)
Explicit interface implemetation Private method IDropTarget.OnDragOver Infrastructure. Raises the DragOver event. (Inherited from Control.)
Top

The ListBox control enables you to display a list of items to the user that the user can select by clicking. A ListBox control can provide single or multiple selections using the SelectionMode property. The ListBox also provides the MultiColumn property to enable the display of items in columns instead of a straight vertical list of items. With this, the control can display more visible items and the user no longer needs to scroll to an item.

Typically, Windows handles the task of drawing the items to display in the ListBox. You can use the DrawMode property, and handle the MeasureItem and DrawItem events so you can override the automatic drawing that Windows provides and draw the items yourself. You can use owner-drawn ListBox controls to display variable-height items, images, or a different color or font for the text of each item in the list. The HorizontalExtent property, GetItemHeight, and GetItemRectangle also help you draw your own items.

In addition to display and selection functionality, the ListBox also provides features that enable you to efficiently add items to the ListBox and to find text within the items of the list. The BeginUpdate and EndUpdate methods enable you to add a large number of items to the ListBox without the control being repainted each time an item is added to the list. The FindString and FindStringExact methods enable you to search for an item in the list that contains a specific search string.

The Items, SelectedItems, and SelectedIndices properties provide access to the three collections that are used by the ListBox. The following table outlines the three collections used by the ListBox and their use within the control.

Collection class

Use within the ListBox

ListBox.ObjectCollection

Contains all items contained in the ListBox control.

ListBox.SelectedObjectCollection

Contains a collection of the selected items which is a subset of the items contained in the ListBox control.

ListBox.SelectedIndexCollection

Contains a collection of the selected indexes, which is a subset of the indexes of the ListBox.ObjectCollection. These indexes specify items that are selected.

The following three examples show the three indexed collections that the ListBox class supports.

The following table shows an example of how the ListBox.ObjectCollection stores the items of the ListBox as well as their selection state within an example ListBox.

Index

Item

Selection state within the ListBox

0

object1

Unselected

1

object2

Selected

2

object3

Unselected

3

object4

Selected

4

object5

Selected

Based on the ListBox.ObjectCollection shown in the previous table, this table shows how the ListBox.SelectedObjectCollection would appear.

Index

Item

0

object2

1

object4

2

object5

Based on the ListBox.ObjectCollection shown in the previous table, this table shows how the ListBox.SelectedIndexCollection would appear.

Index

Index of item

0

1

1

3

2

4

The Add method of the ListBox.ObjectCollection class enables you to add items to the ListBox. The Add method can accept any object when adding a member to the ListBox. When an object is being added to the ListBox, the control uses the text defined in the ToString method of the object unless a member name within the object is specified in the DisplayMember property. In addition to adding items using the Add method of the ListBox.ObjectCollection class you can also add items using the DataSource property of the ListControl class.

Note Note

If you have a ListBox, ComboBox, or CheckedListBox on a base Windows form and want to modify the string collections of those controls in a derived Windows form, the string collections of those controls in the base Windows form must be empty. If the string collections are not empty, they become read-only when you derive another Windows form.

The following code example demonstrates how to create a ListBox control that displays multiple items in columns and can have more than one item selected in the control's list. The code for the example adds 50 items to the ListBox using the Add method of the ListBox.ObjectCollection class and then selects three items from the list using the SetSelected method. The code then displays values from the ListBox.SelectedObjectCollection collection, through the SelectedItems property, and the ListBox.SelectedIndexCollection, through the SelectedIndices property. This example requires that the code is located in and called from a Form.


private void button1_Click(object sender, System.EventArgs e)
{
   // Create an instance of the ListBox.
   ListBox listBox1 = new ListBox();
   // Set the size and location of the ListBox.
   listBox1.Size = new System.Drawing.Size(200, 100);
   listBox1.Location = new System.Drawing.Point(10,10);
   // Add the ListBox to the form.
   this.Controls.Add(listBox1);
   // Set the ListBox to display items in multiple columns.
   listBox1.MultiColumn = true;
   // Set the selection mode to multiple and extended.
   listBox1.SelectionMode = SelectionMode.MultiExtended;

   // Shutdown the painting of the ListBox as items are added.
   listBox1.BeginUpdate();
   // Loop through and add 50 items to the ListBox.
   for (int x = 1; x <= 50; x++)
   {
      listBox1.Items.Add("Item " + x.ToString());
   }
   // Allow the ListBox to repaint and display the new items.
   listBox1.EndUpdate();

   // Select three items from the ListBox.
   listBox1.SetSelected(1, true);
   listBox1.SetSelected(3, true);
   listBox1.SetSelected(5, true);

   // Display the second selected item in the ListBox to the console.
   System.Diagnostics.Debug.WriteLine(listBox1.SelectedItems[1].ToString());
   // Display the index of the first selected item in the ListBox.
   System.Diagnostics.Debug.WriteLine(listBox1.SelectedIndices[0].ToString());             
}



.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
C# ListBoxClass - Adding and Removing Items
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ListBoxClass
{
    public partial class Form1 : Form
    {
        ListBox listBox1 = new ListBox();
        Label label1 = new Label();
        TextBox textBox1 = new TextBox();
        Button button1 = new Button();
        Button button2 = new Button();
        public void SetupControls()
        {           
            this.ClientSize = new Size(368, 262);          
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.Text = Application.ProductName + " - " + listBox1.Items.Count.ToString() + " items";
            listBox1.Height = 225;
            listBox1.Dock = DockStyle.Top;
            listBox1.TabIndex = 1;
            listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
            label1.Location = new Point(12, 236);
            label1.Text = "Item text:";
            label1.AutoSize = true;
            textBox1.Location = new Point(68, 233);
            textBox1.Size = new Size(123, 20);
            textBox1.TabIndex = 2;
            textBox1.TextChanged += new EventHandler(textBox1_TextChanged);
            button1.Enabled = false;
            button1.Location = new Point(197, 231);          
            button1.TabIndex = 3;
            button1.Text = "Add";
            button1.Click += new EventHandler(button1_Click);
          
            button2.Enabled = false;
            button2.Location = new Point(278, 231);
            button2.Size = new Size(75, 23);
            button2.TabIndex = 4;
            button2.Text = "Remove";
            button2.Click += new EventHandler(button2_Click);
        }
        public void AddControls()
        {
            this.Controls.Add(listBox1);
            this.Controls.Add(label1);
            this.Controls.Add(textBox1);
            this.Controls.Add(button1);
            this.Controls.Add(button2);
        }
        public Form1()
        {
            InitializeComponent();
            SetupControls();
            AddControls();          
        }
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedItems.Count != 0)
            {
                button2.Enabled = true;
            }
            else
            {
                button2.Enabled = false;
            }
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text != "")
            {
                button1.Enabled = true;
            }
            else
            {
                button1.Enabled = false;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (!listBox1.Items.Contains(textBox1.Text))
            {
                listBox1.Items.Add(textBox1.Text);
                this.Text = Application.ProductName + " - " + listBox1.Items.Count.ToString() + " items";
                textBox1.Text = "";
                textBox1.Focus();
            }
            else
            {
                MessageBox.Show("This item already exists!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure?", "Remove item", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                listBox1.Items.RemoveAt(listBox1.SelectedIndex);
                this.Text = Application.ProductName + " - " + listBox1.Items.Count.ToString() + " items";
                button2.Enabled = false;
            }
        }
    }
}
Example of binding to DataAdapter?
Any chance of an example showing how to bind to DataAdapter please?
ToString()
The ListBox uses the objects ToString() method for the display text. Override it to customize the display. Nice and simple. HOWEVER, if your ToString returns null, ListBox.Add(object) will throw an Out of Memory Exception, with a "There are too many list items" message. A GB a RAM won't help, just fix your ToString() method.
F# Example

button1.Click.Add(fun e-> 

    let listBox1 = new ListBox()
    // Set the size and location of the ListBox.
    listBox1.Size <- new System.Drawing.Size(200, 100)
    listBox1.Location <- new System.Drawing.Point(10,10)
    // Add the ListBox to the form.
    form.Controls.Add(listBox1)
    // Set the ListBox to display items in multiple columns.
    listBox1.MultiColumn <- true
    // Set the selection mode to multiple and extended.
    listBox1.SelectionMode <- SelectionMode.MultiExtended
    // Shutdown the painting of the ListBox as items are added.
    listBox1.BeginUpdate()
    // Loop through and add 50 items to the ListBox.
    for x in 1..50 do
    listBox1.Items.Add("Item " + x.ToString())|>ignore
    // Allow the ListBox to repaint and display the new items.
    listBox1.EndUpdate()
    // Select three items from the ListBox.
    listBox1.SetSelected(1, true)
    listBox1.SetSelected(3, true)
    listBox1.SetSelected(5, true)
    // Display the second selected item in the ListBox to the console.
    System.Diagnostics.Debug.WriteLine(listBox1.SelectedItems.[1].ToString())
    // Display the index of the first selected item in the ListBox.
    System.Diagnostics.Debug.WriteLine(listBox1.SelectedIndices.[0].ToString()) 
    )