CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2011
    Posts
    7

    New to C# - Loop control events

    I know C++ but started learning C# yesterday.

    In my windows application form I have a button, with a _Click method. I want the program to change between three separate font background colors every time the user clicks the button. When it reaches the 3rd click, the variable 'count' resets to 0 so it starts over at the first color. However, when I run the following program and click the button, it freezes . I know it's an infinite loop within the while loop, but am not sure about the dynamics of C# and .NET, and how I might pause the program after one pass through the while loop, until the button is clicked again. I have a slight idea about what is going on, but not really. Can you help me get this to work or tell me whats wrong?

    Code:
    namespace Fun_with_if_else_statements
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            static int count = 0;
            private void button1_Click(object sender, EventArgs e)
            {
                if (checkBox1.Checked == true)
                {
                    while (count <= 2)
                    {
                        if (count == 0)
                            label1.BackColor = System.Drawing.Color.Blue;
                        if (count == 1)
                            label1.BackColor = System.Drawing.Color.Orange;
                        if (count == 2)
                            label1.BackColor = System.Drawing.Color.Black;
    
                        if (count == 2)
                            count = 0;
                        else
                            count++;
                    }
                }
                else
                {
                    MessageBox.Show("You must check the enable color changing checkbox\nto allow a change in the font background color.");
                }
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                Close();
            }
        }
    }
    Last edited by rcastoro; April 29th, 2013 at 01:02 PM.

  2. #2
    Join Date
    Oct 2011
    Posts
    7

    Re: New to C# - Loop control events

    Please forgive my ignorance. I've been doing so many loops in C++ that I added an unnecessary while loop. I removed it, and kept the if statements, and all works well! Thanks though.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured