Disable item in listbox

Does anybody know how to disable a particular item in a listbox   I know how to disable every single item but have a need to disable certain items only to display them (greyed out) but not let the user select them.

Any suggestions would be appreciated.

C


Answer this question

Disable item in listbox

  • Navaron

    Thanks so much for your reply.  I will definitely try this.

    C

  • JeffreyCollins

    C,

    I had the same problem, this is my solution: 

    1.  Create your own class for adding to the item collection of the listbox which contains a selectable property that you set to true or false.
    2. Set the lisbox control to userdraw and implement the DrawItem event code like below


    Private Sub ListBox_DrawItem(ByVal sender As Object, ByVal e As DrawItemEventArgs) Handles lbDataSelect.DrawItem
            e.DrawBackground()

            Dim drawFont As Font = e.Font
            Dim lCategory As Boolean = False
            Dim lListItem As clsListItemCollection.ListItem = DirectCast(lbDataSelect.Items.Item(e.Index), clsListItemCollection.ListItem)
            If lListItem.ListItemType = clsListItemCollection.ListItem.ItemType.NonSelectable Then lCategory = True

            Dim lCheckBoxWidth As Integer = 15
            If lCategory Then lCheckBoxWidth = 0

            Dim lStringRectf As New RectangleF(e.Bounds.X + lCheckBoxWidth, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height)
            Dim lCheckBoxRect As New Rectangle(e.Bounds.X, e.Bounds.Y, lCheckBoxWidth, e.Bounds.Height)

            Dim lItemSelected As Boolean = ((e.State And DrawItemState.Selected) = DrawItemState.Selected)
            If lItemSelected And Not lCategory Then
                Dim myBrush As Brush = New System.Drawing.SolidBrush(e.ForeColor)
                e.Graphics.FillRectangle(myBrush, e.Bounds)
                ControlPaint.DrawCheckBox(e.Graphics, lCheckBoxRect, ButtonState.Checked)
                e.Graphics.DrawString(lbDataSelect.Items(e.Index).ToString(), drawFont, New SolidBrush(e.BackColor), lStringRectf)
            ElseIf lItemSelected And lCategory Then
                Dim myBrush As Brush = New System.Drawing.SolidBrush(e.ForeColor)
                e.Graphics.FillRectangle(myBrush, e.Bounds)
                e.Graphics.DrawString(lbDataSelect.Items(e.Index).ToString(), drawFont, New SolidBrush(Color.Black), lStringRectf)
            Else
                e.Graphics.DrawString(lbDataSelect.Items(e.Index).ToString(), drawFont, New SolidBrush(e.ForeColor), lStringRectf)
            End If

            e.DrawFocusRectangle()

        End Sub

  • Disable item in listbox