如何在赢取表单中隐藏combobox中的特定项目

如何从combobox中隐藏特定数量的项目。 下面的代码将隐藏所有项目。 我找不到办法执行此操作

string taskSelection = taskSelectionComboBox.Text; string stateOfChild = stateOfChildComboBox.Text; if (stateOfChild == "Awake") { taskSelectionComboBox.Hide(); } 

您需要存储所需的项目,然后使用删除方法删除它们。 你可以使用add来恢复它们。

 // keep the items in a list List list = new List(); list.Add("Awake"); // remove them from combobox comboBox1.Items.Remove("Awake"); // if you want to add them again. comboBox1.Items.Add(list[0]); 

我建议你看看DrawItemMeasureItem事件,然后在其中制作你的逻辑。

 // this is crucial as it gives the the measurement and drawing capabilities // to the item itself instead of a parent ( ComboBox ) taskSelectionComboBox.DrawMode = DrawMode.OwnerDrawVariable; taskSelectionComboBox.DrawItem +=TaskSelectionDrawItem; taskSelectionComboBox.MeasureItem += TaskSelectionMeasureItem; 

然后在TaskSelectionMeasureItem方法内部将高度设置为0

 void TaskSelectionMeasureItem(object sender, MeasureItemEventArgs e) { if(/* check if you want to draw item positioned on index e.Index */ !CanDraw(e.Index) // or whatever else to determine ) e.ItemHeight = 0; } 

之后在绘图方法( TaskSelectionDrawItem )中,您可以再次检查它,并绘制或不绘制该特定元素:

 void TaskSelectionDrawItem(object sender, DrawItemEventArgs e) { if(CanDraw(e.Index)) { Brush foregroundBrush = Brushes.Black; e.DrawBackground(); e.Graphics.DrawString( taskSelectionComboBox.Items[e.Index].ToString(), e.Font, foregroundBrush, e.Bounds, StringFormat.GenericDefault ); e.DrawFocusRectangle(); } } 

另一种方法是使用combobox的DataSource

 var originalTasks = new List { "One", "Two", "Three", "Awake" }; taskSelectionComboBox.DataSource = originalTasks; 

然后,您将通过仅为要显示的项目重新分配DataSource来隐藏项目

 taskSelectionComboBox.DataSource = originalTasks.Where(item => item != "Awake").ToList(); 

再显示所有项目

 taskSelectionComboBox.DataSource = originalTasks; 

此方法适用于任何类型的项目。