使项目不可用于组合框中的选择

再会。我在互联网上搜索并找不到它。请告诉我如何使该项目无法在组合框中选择。这样它就会显示在列表框中,但您无法选择它...

回答

如果您想将它添加到 ComboBox 中,但不能选择,您需要做两件事:

一种。画出来让用户知道它不能被选中

为此,您需要DrawItem根据是否希望它们显示为可选择的方式来绘制控件,订阅事件并以不同的方式呈现项目

湾 在实际选择事件中,取消选择

为此,您需要处理该SelectedIndexChanged事件。一种想法是跟踪当前索引,如果用户选择了不需要的项目,则恢复到先前选择的项目。

在下面的代码中,我将不需要的第二项绘制为红色,跟踪当前索引并取消选择。

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


以上是使项目不可用于组合框中的选择的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>