Reputation: 90
I have 10 strings, all named q1,q2,q3, etc.
My question is, on button click, how do I make them cycle and display within a button?
Current code:
private void nButton_Click(object sender, EventArgs e)
{
for (int g = 0; g <= 10; g++)
{
rBox.Text = q(g);
}
}
Clearly q(g) does not cycle appropriately, so I have come to you, Oracles of code, how would I accomplish this?
** Alternatively, if I wanted to remove the for loop, and instead would just want to increment g by one every time until 10, I assume the structure would resemble something like the following:
private void nButton_Click(object sender, EventArgs e)
{
g++
rBox.Text = q(g);
}
However the question persists, how would I cycle through these strings?
EDIT: I've discovered these neat things called Lists, so I simply created a new list with
List<string> questionNumber = new List<string>();
Then add the string
questionNumber.Add(q1);
As lastly display it through the text box with simple incrementation
private void nButton_Click(object sender, EventArgs e)
{
g++;
rBox.Text = questionNumber[g];
}
Upvotes: 0
Views: 930
Reputation: 101681
The easiest way would be putting them into an array and iterate over the array whenever you wanna operate on your strings.For example:
var values = new [] { q1, q2, q3, ... };
for (int g = 0; g < 10; g++)
{
rBox.Text += values[g];
}
If your intention was to display one string at a time, on each click you can do so by creating a counter variable outside of the click event and increment it per click and just fecth the string at that index:
int index = 0;
private void nButton_Click(object sender, EventArgs e)
{
if(index != values.Length)
{
rBox.Text = values[index];
index++;
}
}
You need to declare values
a field or property of your class, and initialize it with your strings.In fact you can completely remove the variables and just use an array or list to store your values.
Upvotes: 3