首页 > 解决方案 > 如何禁用 ComboBox 中的第一个选项?

问题描述

我已经创建了一个comboboxwithDropDownStyle属性DropDownList,我正在尝试禁用下拉列表的第一个选项(只读),因为这应该类似于“选择一个选项”。

我该怎么做?HTML 中的等效代码应该是这样的:

<option selected disabled>Select an option</option>

只是我在 c# 中实际想要实现的 html 演示。

在此处输入图像描述 在此处输入图像描述

顺便说一句,我正在使用Visual C# Windows Forms App (.NET Framework)

标签: c#.netwinformscombobox

解决方案


那这个呢:

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    var yourFont = new Font("Microsoft Sans Serif", 9, FontStyle.Regular);

    if (e.Index == 0)
    {
        e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), yourFont, Brushes.LightGray, e.Bounds);
    }
    else
    {
        e.DrawBackground();
        e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), yourFont, Brushes.Black, e.Bounds);
        e.DrawFocusRectangle();
    }
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox1.SelectedIndex == 0)
        comboBox1.SelectedIndex = -1;
}

您还需要将 的DrawMode属性设置comboBoxOwnerDrawFixed


推荐阅读