如何使组合框输入无法选择

时间:2017-01-23 11:48:00

标签: vb.net combobox

我有一个带有几个条目的组合框:

-- Europe --
Germany
France
Spain
[...]

-- North America --
Canada
[...]

现在我想让continent-entries无法选择(或禁用),因此用户无法选择它们。为实现这一目标,我尝试了以下方法,但它似乎不起作用:

ComboBox1.Items.Item(0).properties("disabled", True)

还有其他方法可以让条目无法选择吗?

提前致谢

1 个答案:

答案 0 :(得分:0)

在使用下面的代码之前,将combobox1的DrawMode属性设置为OwnerDrawFixed。使用组合框的DrawItem事件。

 Imports System
    Imports System.Drawing
    Imports System.Windows.Forms

    Public Class Form1
        Dim DisabledList As New List(Of String)

        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            DisabledList.Add("Asia")
            DisabledList.Add("Europe")
        End Sub

        Private Sub ComboBox1_DrawItem(ByVal sender As Object, ByVal e As DrawItemEventArgs) Handles ComboBox1.DrawItem
            Dim ItemFont1 As New Font("Arial", 8, FontStyle.Regular)
            Dim ItemFont2 As New Font("Arial", 12, FontStyle.Regular)
            Dim CurrentItem As String = DirectCast(sender, ComboBox).Items(e.Index)

            Using w As New SolidBrush(Color.White)
                e.Graphics.FillRectangle(w, e.Bounds)
            End Using

            If DisabledList.Contains(CurrentItem) Then
                Using b As New SolidBrush(Color.Gray)
                    e.Graphics.DrawString(CurrentItem, ItemFont2, b, e.Bounds.X, e.Bounds.Y)
                End Using
            Else
                e.Graphics.DrawString(CurrentItem, ItemFont1, Brushes.Black, e.Bounds.X, e.Bounds.Y)
            End If
        End Sub
'this event below is to handle if the user select the disabled option then option 'below it is selected. This below code only handle for the disabled item at 'index 0. you can add other index too.
       Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
        Dim comboBox As ComboBox = CType(sender, ComboBox)

        Dim selectedIndex As Integer = comboBox.SelectedIndex
        If selectedIndex = 0 Then
            comboBox.SelectedIndex = selectedIndex + 1
        End If
    End Sub
    End Class

如果有任何混淆让我知道。