Things You'll Need:
- Microsoft Visual C# 2008 Express (free)
-
Step 1
Note: This article assumes you have installed Microsoft Visual C# 2008 Express Edition. You may download it for free from here: http://www.microsoft.com/express/download/
Open Microsoft Visual C#. Click on "Project..." to the right of Create in the Recent Projects area of the Start Page. -
Step 2
The New Project window will open. Click on "Windows Forms Application", enter a Name, and click OK.
By default, the only form in the project will be called "Form1" and you will be in Design mode for that form. -
Step 3
Hover over the Toolbox on the left side of the screen and the Toolbox will automatically expand. Click and drag a Button control, under the Common Controls category, onto the form.
-
Step 4
Double click the button and you will now be in the code window for Form1. The method for the button click will already be created.
-
Step 5
Add our loop within the button1_Click method.
// Classic Hello World Example:
string[] MyStringArray = { "Hello", "World!" };
for (int i = 0; i < MyStringArray.Length; ++i)
{
MessageBox.Show(MyStringArray[i]);
}
This 'for' loop will use an integer variable called "i" to loop through an array of strings. For each element in the array, it will pop-up a message box and display the string in the box. The string displayed will be the element of the array with the same number as the integer i:
When i = 0, MyStringArray[i] = MyStringArray[0] = "Hello".
When i = 1, MyStringArray[i] = MyStringArray[1] = "World!".
The 'for' loop has 4 parts: initialize, compare, process, and increment.
In our example "initialize" is setting the integer i to the value 0:
int i = 0;
Notice that i starts at 0. This is because the first element in an array is numbered as 0.
Our "compare" compares the value of i to the length of the string. The length of the string is 2 so the loop will be executed two times:
i < MyStringArray.Length;
Note: Length is a property of the Array class and returns an Integer that can be compared to the integer i. If you hover over objects in Visual Studio 2008, you will get a context pop-up with extremely valuable information about the object.
The "process" step pops up a MessageBox and displays the string:
MessageBox.Show(MyStringArray[i]);
Finally, i is incremented by 1:
++i
Immediately after the increment, the comparison portion of the loop executes again. -
Step 6
Go up to the toolbar and run the program by clicking on the Start Debugging (f5) play button. The form will take a moment and then pop up. Clicking on the button1 will display the MessageBoxes with our strings in it.
NOTE: If you got any kind of error after clicking the play button, you probably made a syntax error when typing the code. Programming is a precise science. Reread the code until you find and correct the error and try again.











