如何在弹出窗口中禁用组合框中的项目

时间:2019-04-05 04:44:58

标签: c# winforms combobox

是否可以根据条件禁用组合框内的特定项目。需要在组合框点击时显示,即在弹出窗口中显示

1 个答案:

答案 0 :(得分:1)

步骤1.将DrawMode的属性ComboBox设置为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();
     }
 }

Sample Image