Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering text on a button in a WinForms application

Tags:

c#

winforms

I have a simple Windows Forms application with a tabControl. I have 3 panels on the tabControl, each having 5 buttons. The text on first set of buttons is hard-coded, but the next set populates when you click one from the first group, and then the same thing happens again for the last group when you click one of the buttons from the second group. In the [Design] view I manually set the TextAlign property of each button to MiddleCenter. However, when I run the application the text on the middle set of buttons is never centered. It is always TopLeft aligned. I've tried changing the font size and even explicitly setting the TextAlign property every time I set button text programmatically, as follows:

private void setButtons(List<string> labels, Button[] buttons)
    {
        for (int i = 0; i < buttons.Count(); i++)
        {
            if (i < labels.Count)
            {
                buttons[i].Text = labels.ElementAt(i);
                buttons[i].TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
                buttons[i].Enabled = true;
            }
            else
            {
                buttons[i].Text = "";
                buttons[i].Enabled = false;
            }
        }
    }

This image shows the result: alignment issue

Does anyone have any ideas for what I'm missing?

like image 471
Weston Odom Avatar asked Jan 23 '13 15:01

Weston Odom


People also ask

How do I center a button in Windows Forms?

From the Format menu, choose Center in Form.


1 Answers

Trim text which you are assign to button. Also you can refer label by index, without calling ElementAt

private void setButtons(List<string> labels, Button[] buttons)
{
    for (int i = 0; i < buttons.Count(); i++)
    {
        Button button = buttons[i];

        if (i < labels.Count)
        {
            button.Text = labels[i].Trim(); // trim text here
            // button.TextAlign = ContentAlignment.MiddleCenter;
            button.Enabled = true;
        }
        else
        {
            button.Text = "";
            button.Enabled = false;
        }
    }
}
like image 69
Sergey Berezovskiy Avatar answered Oct 25 '22 12:10

Sergey Berezovskiy