gpt4 book ai didi

c# - 禁用组合框中的特定项目

转载 作者:太空宇宙 更新时间:2023-11-03 16:00:59 26 4
gpt4 key购买 nike

我有一个 WinForms 应用程序,我想知道是否有更优雅的方法来禁用组合框项目而不更改所有禁用值的 SelectedIndex 属性 -1。

我一直在谷歌搜索,很多解决方案都涉及 ASP.Net DropDownLists 但这个 LINK看起来很有前途。我想我可能必须构建自己的 ComboBox 控件,但在我重新发明轮子之前,我想我会在这里询问是否可能。

更新

这是最终的解决方案,感谢 Arif Eqbal:

//Add a Combobox to a form and name it comboBox1
//
using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
this.comboBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.comboBox1_DrawItem);
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
}

private void Form1_Load(object sender, EventArgs e)
{
this.comboBox1.Items.Add("Test1");
this.comboBox1.Items.Add("Test2");
this.comboBox1.Items.Add("Test3");
this.comboBox1.Items.Add("Test4");
this.comboBox1.Items.Add("Test5");
this.comboBox1.Items.Add("Test6");
this.comboBox1.Items.Add("Test7");
}

Font myFont = new Font("Aerial", 10, FontStyle.Underline|FontStyle.Regular);
Font myFont2 = new Font("Aerial", 10, FontStyle.Italic|FontStyle.Strikeout);

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index == 1 || e.Index == 4 || e.Index == 5)//We are disabling item based on Index, you can have your logic here
{
e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), myFont2, Brushes.LightSlateGray, e.Bounds);
}
else
{
e.DrawBackground();
e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), myFont, Brushes.Black, e.Bounds);
e.DrawFocusRectangle();
}
}

void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 1 || comboBox1.SelectedIndex == 4 || comboBox1.SelectedIndex == 5)
comboBox1.SelectedIndex = -1;
}
}
}

最佳答案

试试这个……它是否符合您的目的:

我假设您有一个名为 ComboBox1 的组合框,并且您想要禁用第二个项目,即索引为 1 的项目。

将组合框的 DrawMode 属性设置为 OwnerDrawFixed 然后处理这两个事件,如下所示:

Font myFont = new Font("Aerial", 10, FontStyle.Regular);

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index == 1) //We are disabling item based on Index, you can have your logic here
{
e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), myFont, Brushes.LightGray, e.Bounds);
}
else
{
e.DrawBackground();
e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), myFont, Brushes.Black, e.Bounds);
e.DrawFocusRectangle();
}
}

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

关于c# - 禁用组合框中的特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21422736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com