【问题标题】:make item unavailable for selection in combobox使组合框中的项目无法选择
【发布时间】:2021-06-04 04:12:17
【问题描述】:

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

【问题讨论】:

  • 能否为平台(Web、WinForms、WPF)添加标签?
  • 不要在数据源中选择它?
  • 您可以处理组合框SelectedIndexChanged 事件,如果它对应于您不希望用户选择的值,请采取适当的措施

标签: vb.net winforms combobox


【解决方案1】:

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

一个。画出来让用户知道不能选中

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

b.在实际的选择事件中,取消选择

为此,您需要处理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

【讨论】:

  • 与 Draw 的良好接触。
  • 我也喜欢自定义 DrawItem 的想法以及它跳过项目的方式。对于 OP,我想添加一个使用 StrikeOut 字体样式的建议
【解决方案2】:

如果用户通过SelectedIndexChanged 选择了任何不需要的选项,请避免选择

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    相关资源
    最近更新 更多