Archi
Archi

Reputation: 43

make item unavailable for selection in combobox

Good day. I searched the internet and could not find it. Please tell me how to make the item unavailable for selection in the combobox. So that it will be displayed in the list box, but you cannot select it ...

Upvotes: 1

Views: 288

Answers (2)

Devmyselz
Devmyselz

Reputation: 460

Avoid the selection in case user selected any option not desired, via on SelectedIndexChanged

Upvotes: 0

Spyros P.
Spyros P.

Reputation: 296

If you want to have it added in the ComboBox, but not be selectable, you need two things:

a. Draw it so that the user knows that it cannot be selected

For this, you need to owner-draw the Control, subscribe to the DrawItem event and present the items differently, based on whether you want them to appear as selectable or not

b. In the actual selection event, cancel the selection

For this, you need to handle the SelectedIndexChanged event. One idea is to track the current index and if the user selects an unwanted item, revert to the previously selected.

In the code below, I draw the unwanted second item in red, track the current index and cancel the selection.

Dim currentIndex As Integer = -1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ComboBox1.Items.AddRange({"one", "two", "three"})
    ComboBox1.DrawMode = DrawMode.OwnerDrawFixed
    ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList
End Sub

Private Sub ComboBox1_DrawItem(sender As Object, e As DrawItemEventArgs) Handles ComboBox1.DrawItem
    Dim g As Graphics = e.Graphics
    If e.Index <> 1 Then e.DrawBackground()
    Dim myBrush As Brush = Brushes.Black
    If e.Index = 1 Then
        myBrush = Brushes.Red
    End If
    If e.Index <> -1 Then
        e.Graphics.DrawString(ComboBox1.Items(e.Index).ToString(),
            e.Font, myBrush, e.Bounds, StringFormat.GenericDefault)
    End If
    e.DrawFocusRectangle()
End Sub

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    If ComboBox1.SelectedIndex = 1 Then
        ComboBox1.SelectedIndex = currentIndex
    Else
        currentIndex = ComboBox1.SelectedIndex
    End If
End Sub

Upvotes: 5

Related Questions