根据条件为comboBox着色文本

时间:2020-04-07 00:00:19

标签: c# combobox

我有以下代码填充comboBox。来自数据库的项目的布尔值设置为true或false。如果布尔值设置为true,我想将这些项目涂成红色。我绑定comboBoxes的代码看起来像

            if (HasCoded) {
            listAnestheticMeds= new List<AnesthMedsInventory>();
            listAnestheticMeds = AnesthMeds.CreateObject();
            for (int i = 0; i < listAnestheticMeds.Count; i++) {
                if (listAnestheticMeds[i].Hidden == false && listAnestheticMeds[i].IsEmergencyMed) {
                    this.comboAnesthMed.Items.Add(listAnestheticMeds[i].AnesthMedName.ToString());

                }
            }
        }

带有另一个循环,如果条件为假(为简洁起见,则省略),该循环将项目添加到comboBox中。从我读过的书中,我需要将DrawMode设置为OwnerDrawVariable,但不确定如何在_DrawItemEvent处理程序中编写代码以与我的代码块一起使用。

1 个答案:

答案 0 :(得分:0)

确定解决。

这是完整的解决方案:

        private void comboAnesthMed_MeasureItem(object sender,
        System.Windows.Forms.MeasureItemEventArgs e) {
        e.ItemHeight = 12;
        e.ItemWidth = 160;
    }

    private void comboAnesthMed_DrawItem(object sender, DrawItemEventArgs e) {
        // Draw the background 
        e.DrawBackground();
        // Determine the forecolor based on whether or not the item is selected    
        HasCoded = Convert.ToBoolean(AnestheticRecords.GetCodeStatus(anestheticRecordNum));
        if (HasCoded) {
            listAnestheticMeds = new List<AnesthMedsInventory>();
            listAnestheticMeds = AnesthMeds.CreateObject();
            for (int i = 0; i < listAnestheticMeds.Count; i++) {
                IsEmergencyMed = new string[listAnestheticMeds.Count];
                if (listAnestheticMeds[i].Hidden == false && listAnestheticMeds[i].IsEmergencyMed) {
                    if (comboAnesthMed.Items[e.Index].ToString() == listAnestheticMeds[i].AnesthMedName.ToString()) {
                        brush = Brushes.Red;
                    }
                }
                if (listAnestheticMeds[i].Hidden == false &! listAnestheticMeds[i].IsEmergencyMed) {
                    if (comboAnesthMed.Items[e.Index].ToString() == listAnestheticMeds[i].AnesthMedName.ToString()) {
                        brush = Brushes.Black;
                    }
                }

            }
        }
        // Draw the text    
        e.Graphics.DrawString(comboAnesthMed.Items[e.Index].ToString(), ((Control)sender).Font, brush, e.Bounds.X, e.Bounds.Y) ;
    }
相关问题