0% found this document useful (0 votes)
68 views

C# LOOPING in Listbox

The document discusses using a loop to add items to a list box in C#. It explains that a for loop can iterate from a start to end value, performing calculations and adding the results to the list box on each iteration. Specifically, it shows code that multiples two numbers on each loop and adds the results as a string to the list box for display, making the output more readable by including the variables in the string.

Uploaded by

EvelynRubia
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

C# LOOPING in Listbox

The document discusses using a loop to add items to a list box in C#. It explains that a for loop can iterate from a start to end value, performing calculations and adding the results to the list box on each iteration. Specifically, it shows code that multiples two numbers on each loop and adds the results as a string to the list box for display, making the output more readable by including the variables in the string.

Uploaded by

EvelynRubia
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 12

LOOPING

LIST BOX
A list box is used to display lists of items.
Double click your button to get at your code. Now
add this line to your loop:

for (int i = loopStart; i <= loopEnd; i++)


{
answer = answer + i;
listBox1.Items.Add( answer.ToString() );
}
So you start by typing the Name of your list box
(listBox1, for us). After a dot, you should see the
IntelliSense list appear.
Select Items from the list. Items is another
property of list boxes. It refers to the items in
your list.
After the word Items, you type another dot. From
the IntelliSense list, select the Add method. As its
name suggests, the Add method adds items to
your list box.
Between the round brackets, you type what you
want to add to the list of items.
The programme is supposed to add up the
number 1 to 5, or whatever numbers were
typed in the text boxes. The list box is
displaying one answer for every time round
the loop.
To add some more information in list box:

listBox1.Items.Add( "answer = " + answer.ToString( ) );

Typed some direct text "answer=" and


followed this with the concatenation symbol
(+).
C# will then join the two together, and display
the result in your list box.
To make it even clearer, add some more text to
your list box. Try this:
listBox1.Items.Add( "i = " + i + " answer = " + answer.ToString( ) );
int answer = 0;
int loopStart;
int loopEnd;
loopStart = int.Parse(textBox1.Text);
loopEnd = int.Parse(textBox2.Text);
int multiplyBy = int.Parse(textBox3.Text);
listBox1.Items.Clear();
for ( int i = loopStart; i <= loopEnd; i++) {
answer = multiplyBy * i;
listBox1.Items.Add( i + " times " + multiplyBy + " = " +
answer.ToString() );
}

You might also like