Search code examples
c#windowsif-statementnested-if

How can I make a button which swaps between 3 background colors?


So I'm trying to figure out how to have the click of a button swap between 3 background colors in a windows application form. Managed to make it swap between 2, but struggling to move up to three.

The result of ~30 minutes of trying everything that came to mind: https://prnt.sc/1rka67i

The 2 color variation: https://prnt.sc/1rkakrm


Solution

  • In this case you could modify property of Form's backgroud on button click event like:

    private void button1_Click(object sender, EventArgs e)
    {
        this.BackColor = Color.White; //for example 
    }
    

    If you want to swap between 3 colors you could try like:

    int counter = 0;
    private void button1_Click(object sender, EventArgs e)
    {
        counter++;
        if(counter == 1)
            this.BackColor = Color.White; //for example 
        if(counter == 2)
            this.BackColor = Color.Black; //for example 
        if(counter == 3){
            this.BackColor = Color.Gray; //for example 
            counter = 0;
        }
    }