首页 > 解决方案 > 使组合框中的项目无法选择

问题描述

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

标签: vb.netwinformscombobox

解决方案


如果要将其添加到 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

推荐阅读