For loops in window form applications

I just designed a simple "For Loop" using a window form application. I would like it to be clicked once only once and that it won't repeat the same information if I click the button. How could I do this? thanks Here's my code:

        int count;

        for (count = 0; count < 5; count = count + 1)
        {
            listBox1.Items.Add("This is count: " + count);
        }
        const string textEnd = "Done!!!";
        {
            listBox1.Items.Add(textEnd);
        }

      

==== More information === I did it this way. This will only happen once, but the button is still enabled. I think this is ok:

        int count;

        for (count = 0; count < 5; count++)
        {
            string newItem = "This is count: " + count; 
            if (listBox1.Items.IndexOf(newItem) < 0) 
            { 
                listBox1.Items.Add(newItem); 
            }
         }

        const string textEnd = "Done!!!";
        if (listBox1.Items.IndexOf(textEnd) <0)
        {
            listBox1.Items.Add(textEnd);
        }

      

0


a source to share


6 answers


I'm assuming that you don't want the same items to be added to the list multiple times?

Instead

{
    listBox1.Items.Add("This is count: " + count);
}

      



You need something like

{
    string newItem = "This is count: " + count;
    if(listBox1.Items.IndexOf(newItem) < 0)
    {
        listBox1.Items.Add(newItem);
    }
}

      

+1


a source


button1.Enabled = false;

      



+4


a source


On click event add button1.Enabled = false

And maybe after the loop, you may need to add button1.Enabled = true to reuse the button. :)

0


a source


You can simply use a simple flag to determine if the loop has already started.

Create a global variable eg bool HasRun = false;

Then check the state of the flag before doing the loop for example if HasRun == true

Sets HasRun to true when the loop is first run.

Finally, you can also disable the button on first launch eg button1.Enabled = false;

0


a source


If it's not too many items, you can always clear the list before adding material.

listbox1.Items.Clear();
...your adding code...

      

But probably the best solution is to just disable the button, as Jan wrote.

0


a source


Best of all, Ian Said, however, you can also hide the button completely by running any of the following commands

button.Hide();

      

or

button.Visable = false;

      

0


a source







All Articles