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);
}
a source to share
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);
}
}
a source to share
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;
a source to share