0

I want to align DataGridViewComboBoxColumn selections text center when in editmode(when click dropdown). I found an approach here:Align Text in Combobox, to align combobox, and tried to add EditingControlShowing event to DGV, and add DrawItem event like above approach to align combobox, but it didn't work. Here is the code:

private void MyDGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
    {
        ComboBox cb = e.Control as ComboBox;
        if (cb != null)
        {
            cb.DrawItem += new DrawItemEventHandler(cbxDesign_DrawItem);
        }
    }
}
private void cbxDesign_DrawItem(object sender, DrawItemEventArgs e)
{
    // By using Sender, one method could handle multiple ComboBoxes
    ComboBox cbx = sender as ComboBox;
    if (cbx != null)
    {
        // Always draw the background
        e.DrawBackground();

        // Drawing one of the items?
        if (e.Index >= 0)
        {
            // Set the string alignment.  Choices are Center, Near and Far
            StringFormat sf = new StringFormat();
            sf.LineAlignment = StringAlignment.Center;
            sf.Alignment = StringAlignment.Center;

            // Set the Brush to ComboBox ForeColor to maintain any ComboBox color settings
            // Assumes Brush is solid
            Brush brush = new SolidBrush(cbx.ForeColor);

            // If drawing highlighted selection, change brush
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                brush = SystemBrushes.HighlightText;

            // Draw the string
            e.Graphics.DrawString(cbx.Items[e.Index].ToString(), cbx.Font, brush, e.Bounds, sf);
        }
    }
}

Any suggestions? Thanks!

Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
Kamil
  • 594
  • 1
  • 8
  • 28
  • 1
    You know that you can use WPF controls in Winforms? WPF controls give much more style, format options – Basin Aug 10 '18 at 03:19
  • It seems you've missed a paragraph of the answer: *The trick is to set the DrawMode-Property of the ComboBox to OwnerDrawFixed as well as subscribe to its event DrawItem.* – Reza Aghaei Aug 10 '18 at 06:14

1 Answers1

1

In your code you need to add these properties for the code to work:

private void MyDGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
    {
        ComboBox cb = e.Control as ComboBox;
        if (cb != null)
        {
            //add these 2
            cb.DrawMode = DrawMode.OwnerDrawFixed;
            cb.DropDownStyle = ComboBoxStyle.DropDownList;
            cb.DrawItem += new DrawItemEventHandler(cbxDesign_DrawItem);
        }
    }
}