C#: Changing Button BackColor has no effect
Asked Answered
Y

4

5

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, every modification to those buttons (location and size) except for the modification of the BackColor is readily executed. Only the button's color remains unchanged.

The code looks something like this:

public class SimpleSortAlgDisplayer : ISortAlgDisplayer
{

    #region ISortAlgDisplayer Member

    void ISortAlgDisplayer.Init(int[] Data)
    {
        this.DataLength = Data.Length;
        this.DispWin = new CurrentSortStateWin();
        this.DispWin.Show();
        this.DispWin.Size = new Size(60 + (10 * this.DataLength), 120);

        this.myArrayElements = new Button[this.DataLength];
        for (int i = 0; i < this.DataLength; i++)
        {
            this.myArrayElements[i] = new Button();
            //begin of series of invoked actions

            this.myArrayElements[i].Size=new Size(5,(int)(((80)*(double)Data[i])/1000));
            this.myArrayElements[i].Location = new Point(30 + (i * 10), 90-(this.myArrayElements[i].Size.Height));
            this.myArrayElements[i].Enabled = true;
            this.myArrayElements[i].BackColor = Color.MidnightBlue;
            this.myArrayElements[i].UseVisualStyleBackColor = true;
            this.DispWin.Controls.Add(this.myArrayElements[i]);
            this.myArrayElements[i].Refresh();

        }
    }

Ideas anyone?

A similar question was asked here but the answers to it were not very helpful:

  • Trying to use Invoke gives me the run-time error that DispWin is not yet created.
  • Setting UseVisualStyleBackColor to false changes nothing.
  • Setting BackColor and ForeColor or Showing DispWin only after adding and formatting the Buttons also had no effect.

Where am I going wrong?

Yoo answered 19/8, 2011 at 22:11 Comment(8)
Can you post code that produces that problem? I create buttons like you are, but they all have color.Stakeout
@Lionel: what does Refresh do?Synchronism
@LarsTech: My problem is I don't know what code besides the one I posted could be producing the problem. If I knew I probably wouldn't need to post the question. I was hoping that the problem could already be seen from the code I posted.Bakeman
@Tigran: I inserted the refresh action hoping that repainting the buttons would solve the problem. But it doesn't.Bakeman
Add this : myArrayElements[i].Click += (s, a) => Console.WriteLine((s as Button).UseVisualStyleBackColor); - Then run it, click it, and look in the output window (debug). If it says "True" you know something is setting UseVisualStylesBackColor after your creation code.Countdown
(You do need UseVisualStylesBackColor to be false)Countdown
Thanks. I just tried it. But the UseVisualStylesBackColor apparently keeps at the value falseBakeman
So if UseVisualStylesBackColor remains false then this cannot be the cause why changing BackColor has no effect.Bakeman
H
11

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

Hopeh answered 19/8, 2011 at 22:38 Comment(7)
As I wrote I also tried setting UseVisualStyleBackColor to false but also this had no effectBakeman
@Lionel: It's still relevant though since if you try something that fix your other problem, you might not notice it due to this, so definitely remove the UseVisualStyleBackColor line.Simoneaux
Though I think it's only relevant if UseVisualStyleBackColor is set to true before the BackColor is set, since I think setting the BackColor automatically sets UseVisualStyleBackColor to false.Simoneaux
@Lionel Pöffel added github link, fell free to clone it and test it, then debug your own code.Hopeh
thanks for adding the link. I'm not yet seeing where could be the important difference. Of course I tried creating a new Form like your's and, not much surprisingly, setting BackColor worked there. The only idea I have at the moment is that your populate() method is called from an event handler where my method is public and can be called directly if an objyct of type SimpleSortAlgDisplayer has been created.Bakeman
I got it: In the main program.cs Application.EnableVisualStyles() is set by default when creating a windows Forms application. Commenting this out solved the problem (although the buttons don't look as nice. Thanks everyone here.Bakeman
If my answer have helped you, don't forget to upvote or set as correct answer, so others in the future could know what to do easily. :)Hopeh
L
4

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

Looby answered 23/12, 2015 at 6:44 Comment(0)
M
1

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

Metamorphism answered 9/5, 2014 at 18:37 Comment(1)
this tortured me for 18 hours! thank you, removing BackgroundImage solved the problemPresentation
P
0

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.

Prognostic answered 16/10, 2019 at 16:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.