我正在尝试使用DrawItem事件在DataGridView的ComboBoxCell中绘制项目。以下是我的代码。

更新的代码:

private void dgv_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        int index = dgv.CurrentCell.ColumnIndex;
        if (index == FormatColumnIndex)
        {
            var combobox = e.Control as ComboBox;
            if (combobox == null)
                return;
            combobox.DrawMode = DrawMode.OwnerDrawFixed;
            combobox.DrawItem -= combobox_DrawItem;
            combobox.DrawItem += new DrawItemEventHandler(combobox_DrawItem);
        }
    }

void combobox_DrawItem(object sender, DrawItemEventArgs e)
    {
        if (e.Index < 0)
        {
            return;
        }
        int index = dgv.CurrentCell.RowIndex;
        if (index == e.Index)
        {
            DataGridViewComboBoxCell cmbcell = (DataGridViewComboBoxCell)dgv.CurrentRow.Cells["ProductFormat"];

            string productID = dgv.Rows[cmbcell.RowIndex].Cells["ProductID"].Value.ToString();

                string item = cmbcell.Items[e.Index].ToString();
                if (item != null)
                {
                    Font font = new System.Drawing.Font(FontFamily.GenericSansSerif, 8);
                    Brush backgroundColor;
                    Brush textColor;

                    if (e.State == DrawItemState.Selected)
                    {
                        backgroundColor = SystemBrushes.Highlight;
                        textColor = SystemBrushes.HighlightText;
                    }
                    else
                    {
                        backgroundColor = SystemBrushes.Window;
                        textColor = SystemBrushes.WindowText;
                    }
                    if (item == "Preferred" || item == "Other")
                    {
                        font = new Font(font, FontStyle.Bold);
                        backgroundColor = SystemBrushes.Window;
                        textColor = SystemBrushes.WindowText;
                    }


                    if (item != "Select" && item != "Preferred" && item != "Other")
                        e.Graphics.DrawString(item, font, textColor, new Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height));
                    else
                        e.Graphics.DrawString(item, font, textColor, e.Bounds);
                }
            }
        }
    }


这些项目可以正确显示,但是下拉菜单似乎不合适,看起来很尴尬。

另外,当我将鼠标悬停在下拉菜单项上时,它们似乎又被重新绘制,这使它们看起来更暗,更模糊。我怎样才能解决这个问题?谢谢。

最佳答案

您的绘制例程看起来像是将网格的RowIndex与ComboBox项目集合的e.Index混淆了。不同的东西。

尝试删除此:

// int index = dgv.CurrentCell.RowIndex;
// if (index == e.Index) {


就模糊性而言,添加以下行以修复该问题:

void combobox_DrawItem(object sender, DrawItemEventArgs e) {
  e.DrawBackground();

10-06 05:36