C# winform to center the text of the ComboBox control

In C#, when the property DropDownStyle of ComboBox is set to DropDownList, the text of ComboBox2 box is left-aligned by default.

Take ComboBox1 as an example to center the drop-down text and subscribe to events:

 public Form2()
        {
            InitializeComponent();

            comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
            comboBox1.DrawItem + = new DrawItemEventHandler(comboBox1_DrawItem);
            
        }

What this code does is to set the drawing mode of a combo box control named comboBox2 to OwnerDrawFixed, and add an event handler named comboBox2_DrawItem to the DrawItem event of the control.

In C#, the ComboBox control has several drawing modes, including Normal, OwnerDrawFixed, OwnerDrawVariable, and Professional. In Normal mode, the ComboBox control uses the default drawing method to render its items. In the OwnerDrawFixed and OwnerDrawVariable modes, developers can customize the drawing method of the ComboBox control to better meet the needs of the application.

Event of DrawItem of ComboBox1:

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    if (e. Index < 0)
    {
        return;
    }

    e.DrawBackground();

    string text = comboBox1.GetItemText(comboBox1.Items[e.Index]);
    SizeF textSize = e.Graphics.MeasureString(text, comboBox1.Font);

    float left = (float)(e.Bounds.Width - textSize.Width) / 2;
    float top = (float)(e.Bounds.Height - textSize.Height) / 2;

    e.Graphics.DrawString(text, comboBox1.Font, Brushes.Black, e.Bounds.Left + left, e.Bounds.Top + top);

    e.DrawFocusRectangle();
}

This code uses the DrawMode.OwnerDrawFixed property to customize how ComboBox1 is drawn. We then subscribed to the DrawItem event, which fires when each item is drawn. In the event handler, we first draw the background, then get the current item’s text and measure its size. Next, we calculate where the text should be drawn so that it is center-aligned. Finally, we draw the text into ComboBox1 using the Graphics.DrawString method.

The above method only centers the drop-down text, but cannot center the text of the ComboBox1 box, as shown in the figure:

To set the DropDownStyle property of ComboBox1 to center the text of the DropDownList and the text of the ComboBox1 text box, the following steps can be implemented:

  1. Open Visual Studio and open your C# project.
  2. Find the ComboBox1 control, double-click to open its properties window.
  3. Find the DropDownStyle property in the Properties window and set it to DropDownList.
  4. Find the DrawMode property in the Properties window and set it to OwnerDrawFixed.
  5. Find the ItemHeight property in the Properties window and set it to the height of ComboBox1. (This step can be ignored)
  6. Find the DrawItem event in the properties window, double-click to open its code editor.
  7. Add the following code in the code editor:
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e. Index < 0) return;
            e.DrawBackground();
            e.DrawFocusRectangle();
            string text = comboBox1.GetItemText(comboBox1.Items[e.Index]);
            using (StringFormat sf = new StringFormat())
            {
                sf.Alignment = StringAlignment. Center;
                e.Graphics.DrawString(text, e.Font, Brushes.Black, e.Bounds, sf);
            }
        }

8. Save and run your program, the text of ComboBox1 should now be centered.

If you want the ComboBox1 drop-down box and text box to display colorless, you can add this line of code

e.Graphics.FillRectangle(Brushes.White, e.Bounds);

or

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    if (e. Index >= 0)
    {
        string text = comboBox1.Items[e.Index].ToString();
        using (StringFormat sf = new StringFormat())
        {
            sf.Alignment = StringAlignment. Center;
            e.Graphics.DrawString(text, e.Font, Brushes.Black, e.Bounds, sf);
        }
    }
    e.DrawFocusRectangle();
}

The function of this code is to center the text in the drop-down list in the drawing event of the ComboBox control. Specifically, it uses the StringFormat class to set the alignment of the text, and then uses the DrawString method of the Graphics class to draw the text at the specified position.

In the DrawItem event of ComboBox1, center the text of ComboBox1 and display the text in the center, as shown in the figure below:

If only the text of the ComboBox drop-down box is centered, the text in the ComboBox box remains unchanged on the left:

The ComboBox control is a commonly used drop-down list box control. By default, the text of the ComboBox control is center-aligned. If you want to center only the drop-down text of ComboBox1, but not the text of ComboBox1, you can do it through the following steps:

  1. Open Visual Studio and create a Windows Forms application.
  2. Add a ComboBox control on the form.
  3. In the property window of the ComboBox control, find the DropDownStyle property and set it to DropDown.
  4. In the Properties window of the ComboBox control, find the DrawMode property and set it to OwnerDrawFixed.
  5. In the event of the ComboBox control, add the following code:
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    if (e. Index >= 0)
    {
        string text = comboBox1.Items[e.Index].ToString();
        using (StringFormat sf = new StringFormat())
        {
            sf.Alignment = StringAlignment. Center;
            e.Graphics.DrawString(text, e.Font, Brushes.Black, e.Bounds, sf);
        }
    }
    e.DrawFocusRectangle();
}

Not centered by default, in the DrawItem event of ComboBox1:

 e.DrawBackground();
            if (e. Index >= 0)
            {
                StringFormat sf = new StringFormat();
                sf.LineAlignment = StringAlignment.Center;
                e.Graphics.DrawString(comboBox2.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds, sf);
            }

The above method is just for reference, and the actual application can be modified according to the needs. If there is a better method, please add it!

The above content is used to record your own learning and sharing, and sharing makes technology go further!

Technology comes from the innovation of freedom of thought, independent thinking, dialectical analysis, logical thinking and human freedom, to serve the various conveniences of human life, not to create stupidity by using technology to create ideological divides and sieges; technology is good and Bad, good people use technology is better, bad people use technology is worse. Recommended books: George Orwell’s “1984”, Zamyatin’s “Us”, Aldous Huxley’s “Brave New World”, there are multiple translations, just choose the one you like and the good one; There are Plato’s “Utopia”, Montesquieu’s “On the Spirit of Law”, Hayek’s “The Road to Serfdom” (Hong Kong version) (the Hong Kong version has better translation The mainland version, the original English version is best for those with good English), and it is now on sale in online stores! Reading good books, reading books that most people have never read and not in classrooms, and reading knowledge that is not available in this land can increase a kind of speculative thinking and wisdom, and only then can we get out of the cave of narrow thinking and prejudice!

Plato wrote about the cave theory in the seventh volume of his masterpiece “Utopia”: a group of people who were imprisoned and lived in the cave since childhood, under the light outside the cave, saw black shadows inside, Looking out, it is a bright sea and sky, and the more you look, the brighter it is!

A well-informed and tolerant person is more confident and diverse in thinking. A good and tolerant culture makes people stronger. The more confident and tolerant the stronger! Tolerance allows you to use the Internet, telephone, various electrical appliances, automobiles, chips, railways, high-speed rail…