【问题标题】:How to disable an item in combbox on popup show如何在弹出节目中禁用组合框中的项目
【发布时间】:2019-04-05 04:44:57
【问题描述】:

有没有办法根据条件禁用组合框中的特定项目。需要在单击组合框时显示,即在弹出显示时显示

【问题讨论】:

  • 我怀疑您需要所有者绘制控件(进行调光),然后使用选择代码来拒绝任何选择项目的尝试。
  • 实际上,在某种程度上,您添加到 ComboBox 的所有项目都禁用,因为是您的代码对项目选择进行了 something .如果您什么都不做...您的意思是项目应该在视觉上显示为禁用?或者如果特定项目被标记禁用,您的代码不会执行任何操作?两个都?条件是什么?您将哪些类型的项目添加到 ComboBox 以及如何添加?什么是弹出窗口?
  • 是的,项目应该根据条件在弹出窗口中显示为禁用
  • 因此,当您加载ComboBox 时,您需要根据条件禁用项目。为什么不能在将其绑定到ComboBox 之前检查条件并从列表中删除该项目。您能否提供示例或屏幕截图或代码以更清楚地说明。
  • @SH7 让我们说组合框中的项目 {a1,a2}.. 所以条件是如果 a1 然后在弹出显示中禁用组合框中的 a1 项目。

标签: c# winforms combobox


【解决方案1】:

步骤1.将ComboBox的属性DrawMode设置为OwnerDrawFixed

步骤 2. 使用索引值更改项目颜色

 Font fontValue = new Font("calibri", 12, FontStyle.Regular);

 //Form Load
 private void form_Load(object sender, EventArgs e)
 {
    List<string> lstCombxValue = new List<string>();
    lstCombxValue.Add("Item A1");
    //Item to Disable
    lstCombxValue.Add("Item A2");
    lstCombxValue.Add("Item A3");
    lstCombxValue.Add("Item A4");
    lstCombxValue.Add("Item A5");
    lstCombxValue.Add("Item A6");

    comboBox1.DataSource = lstCombxValue;
 }

 private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
 {
     //Check the Condition get the Item Index Value to Disable 
     //and follow this step to disable the item
     if (e.Index == 1)
     {
         e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), fontValue, Brushes.Gray, e.Bounds);
     }
     else
     {
         e.DrawBackground();
         e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), fontValue, Brushes.Black, e.Bounds);
         e.DrawFocusRectangle();
     }
 }

【讨论】:

  • 使用e.Font 作为Font 参数,否则无法正确绘制Combo 项。您还应该使用 e.ForeColor 值作为项目颜色,否则,通常 ComboBox 将与设计器中设置的样式不匹配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 2012-07-11
  • 1970-01-01
相关资源
最近更新 更多