C#: Changing Button BackColor has no effect

后端 未结 4 714
逝去的感伤
逝去的感伤 2021-01-06 18:10

I\'m having a problem with C# buttons in Windows Forms.

I\'ve create a number of buttons programmatically and add them to a form afterwards.

Interestingly, e

相关标签:
4条回答
  • 2021-01-06 18:52

    If FlatStyle for button is set to System, it will not show any backcolor rather use backcolor from template of system colors.

    0 讨论(0)
  • 2021-01-06 19:05

    You are trying to set up the color, but then you override it saying UseVisualStyleBackColor = true

    if you want to use your custom color, you need to set UseVisualStyleBackColor to false or the color will only be applied to the button upon mouse over.

    a simple test uploaded to GitHub

    public partial class mainForm : Form
    {
        Random randonGen = new Random();
    
        public mainForm()
        {
            InitializeComponent();
        }
    
        private void mainForm_Load(object sender, EventArgs e)
        {
            populate();
        }
    
        private void populate()
        {
            Control[] buttonsLeft = createButtons().ToArray();
            Control[] buttonsRight = createButtons().ToArray();
    
            pRight.Controls.AddRange(buttonsRight);
            pLeft.Controls.AddRange(buttonsLeft);
        }
    
        private List<Button> createButtons()
        {
            List<Button> buttons = new List<Button>();
    
            for (int i = 1; i <= 5; i++)
            {
    
                buttons.Add(
                    new Button()
                    {
                        Size = new Size(200, 35),
                        Enabled = true,
                        BackColor = GetColor(),
                        ForeColor = GetColor(),
                        UseVisualStyleBackColor = false,
                        Left = 20,
                        Top = (i * 40),
                        Text = String.Concat("Button ", i)
                    });
            }
    
            return buttons;
        }
    
        private Color GetColor()
        {
            return Color.FromArgb(randonGen.Next(255), randonGen.Next(255), randonGen.Next(255));
        }
    }
    

    result

    enter image description here

    0 讨论(0)
  • 2021-01-06 19:05

    Make sure you do not have a BackgroundImage set. This overrides the BackColor.

    0 讨论(0)
  • 2021-01-06 19:07

    In the properties window for Button. Look for 'FlatStyle' property and change it from 'System' to 'Flat', 'Standard' or 'Popup' and you will be able to see the button color change. I just fixed my issue with this.

    0 讨论(0)
提交回复
热议问题