Centering text on a button in a WinForms application

I have a simple Windows Forms application with tabControl. I have 3 panels on tabControl, each of which has 5 buttons. The text on the first set of buttons is hardcoded, but the next set is filled in when one of the first group is pressed, and then the same thing is repeated for the last group when you press one of the buttons in the second group. In the [Design] view, I manually set the property of TextAligneach button to MiddleCenter. However, when I launch the application, the text on the middle set of buttons is never centered. It is always TopLeftaligned. I tried to change the font size and even explicitly set the property TextAlignevery time I set the 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;
            }
        }
    }

: alignment issue

- , ?

+5
4

, . , 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;
        }
    }
}
+4

SQL, , nchar(50), nvarchar(50), . .Trim() , .

0

TextAlign MiddleCenter...

, , , , ...,

btnFunction.Font = new Font(btnFunction.Font.Name, Convert.ToInt32(btnFunction.Height * 0.3333333333333333));

This will cause the font of the button to be one third of the height of the button ....

0
source

You can set the UseCompatibleTextRendering property to true, and then use the TextAlign property.

0
source

All Articles