c# - 如何禁用 ComboBox 中的第一个选项?
问题描述
我已经创建了一个combobox
withDropDownStyle
属性DropDownList
,我正在尝试禁用下拉列表的第一个选项(只读),因为这应该类似于“选择一个选项”。
我该怎么做?HTML 中的等效代码应该是这样的:
<option selected disabled>Select an option</option>
这只是我在 c# 中实际想要实现的 html 演示。
顺便说一句,我正在使用Visual C# Windows Forms App (.NET Framework)
解决方案
那这个呢:
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
属性设置comboBox
为OwnerDrawFixed
。
推荐阅读
- c - 根据条件执行或跳过 ld.so.preload 共享库代码
- r - 为什么我的 R 循环返回越界错误?
- c# - 如何测试行在 SQL Server 中更新时被锁定
- c# - C#:检测空模型对象时出现空引用异常
- javascript - 试图平滑滚动动画并理解为什么我的文字会瞬间消失
- c# - 如何保存/存储和加载回编辑器窗口更改?
- javascript - 文本和字体真棒图标不会在切换时改变
- java - 我无法从我的应用程序将视频分享到 whatsapp
- python - 无法从 anaconda 中找到 python 模块,使用 pip 安装的模块
- angular - 角度叠加定位 - 它是如何工作的?