How do I loop through a method x amount of times? - c#

I have this project with a method like so.
private void LoopThis()
{
MessageBox.Show("Hello World!");
}
And I have this button that invokes the method, and a textbox where I enter a int let's say i enter 10.
Ten I want that method to execute 10 times.
What kind of loop do I use to do this?

private void Button_Click(object sender, RoutedEventArgs e)
{
int times;
if (Int32.TryParse(TextBox.Text, out times))
{
// It could parse the input text (so we deduce it was an integer)
// and not a string.
for (int i = 0; i < times; i++)
{
LoopThis();
}
}
else
{
// Throw exception or show a message to the user
}
}

Related

Updating a label using a for statement (typewriter effect)

I'm developing a game in Windows Forms (.NET-framework), and I want to add a typewriter effect to the text I'm displaying (so that it displays letter by letter). I'm using a for-loop for this. The text is displayed in a label.
I have 2 variables. 1 that holds all the text, and one that holds the text that needs to be printed out in the loop:
public string FullText;
private string CurrentText = "";
The label that I want to update with the loop is called: LblTextBottom
This is the method that gets executed when I click on the appropriate button:
public void TypeWriterEffect()
{
for(int i=0; i < FullText.Length; i++)
{
CurrentText = FullText.Substring(0, i);
LblTextBottom.Text = CurrentText;
Thread.Sleep(10);
}
}
This is the code that is activated when I click on the button to run the TypeWriterEffect method:
private void Button1_Click(object sender, EventArgs e)
{
FullText = LblTextBottom.Text;
ShowText();
}
It updates the Label, and the code works, but I don't see it updating in real time (the text doesn't get displayed letter by letter). I've tried using separate threads to update the control, but I didn't get that to work.
Ofcourse, I wouldn't be here if this code was working. But I don't know why it won't update. So any help would be greatly appreciated :)
P.s: This is what I'm looking for, but ofcourse without the UnityEngine classes and namespace (can't use those).
EDIT: Forgot to tell that when a button is clicked, a new string of text is loaded into the LblTextBottom, from a different .cs file.
If you write it generically, then you can have multiple typewriters going at the same time:
private async void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
await TypeWriterEffect("This is some text to be `typed`...", LblTextBottom, 100);
button1.Enabled = true;
}
private async void button2_Click(object sender, EventArgs e)
{
button2.Enabled = false;
await TypeWriterEffect("Look mom, we're running at the same time!!!", label2, 200);
button2.Enabled = true;
}
public Task TypeWriterEffect(string txt, Label lbl, int delay)
{
return Task.Run(() =>
{
for (int i = 0; i <= txt.Length; i++)
{
lbl.Invoke((MethodInvoker)delegate {
lbl.Text = txt.Substring(0, i);
});
System.Threading.Thread.Sleep(delay); ;
}
});
}
Producing:

My IF statement is not working in windows form application

I'm trying to create a gym membership with various radio buttons as different options. I want the user to be able to select the calculate button and the cost to appear in the text box but for some reason my if the statement is adding all the radio button costs together instead of just​ the one the user selects.
private void calculatebutton_click(object sender, eventargs e)
{
int membershipcost = 0;
if (basicradiobutton.checked);
membershipcost += 10;
if (regularradiobutton.checked);
membershipcost += 15;
if (premiumradiobutton.checked);
membershipcost += 20;
membershipcosttxtbx.text = membershipcost.tostring();
You need to remove the semicolons from your if statements or format your code like so:
private void calculatebutton_click(object sender, eventargs e)
{
int membershipcost = 0;
if (basicradiobutton.checked)
{
membershipcost += 10;
}
if (regularradiobutton.checked)
{
membershipcost += 15;
}
if (premiumradiobutton.checked)
{
membershipcost += 20;
}
membershipcosttxtbx.text = membershipcost.tostring();
}
Your C# is not written correctly. I suggest to use { & } to define a code block associated with the if condition. You can create a single line if statement, which I have included on the second if. Putting a ; immediately after the if(...) will result in no action from the statement.
private void calculatebutton_click(object sender, eventargs e)
{
int membershipcost = 0;
if (basicradiobutton.checked)
{
membershipcost += 10;
}
if (regularradiobutton.checked) membershipcost += 15;
if (premiumradiobutton.checked)
{
membershipcost += 20;
}
membershipcosttxtbx.text = membershipcost.tostring();
}

Windows Form App Float to String

Below is some of my code that isn't working. I wanted to see it could count the number of spaces in the text box so I'm having it display the number in a message box and it currently just throws a blank one. The problem is either in the float to string conversion or in the counter.
private static string _globalVar = "n";
public static string GlobalVar
{
get { return _globalVar; }
set { _globalVar = value; }
}
public Form1()
{
InitializeComponent();
button1.Text = "Enter";
}
string LNum { get; set; }
public void button1_Click_1(object sender, EventArgs e)
{
MessageBox.Show(LNum);
}
public void richTextBox1_TextChanged(object sender, System.Windows.Forms.KeyEventArgs e)
{
float n = 0;
if (Control.ModifierKeys == Keys.Space)
{
n = n + 1; ;
}
string.Format("{0:N1}", n);
string LNum = Convert.ToString(n);
}
What you are doing is an excellent way to learn how and when the events are raised and how they can be leveraged to customize an applications behavior and is something similar to what many of us have done over the years.
Based on what you say you are wanting to do, there are several issues. If you take a look at this code, it will do what you want.
public void button1_Click(object sender, EventArgs e)
{
int n = 0;
for (int counter = 0; counter < richTextBox1.TextLength; counter++)
{
if (richTextBox1.Text[counter] == ' ')
{
n++;
}
}
MessageBox.Show(n.ToString("N1"));
}
The key difference is that I am only looking at the entered text when the button is clicked. (TextChanged is run every time there is a change in the text displayed). I chose not to use a float variable to store the count of spaces as the count will always be an integer.
In addition, the parameter to TextChanged System.Windows.Forms.KeyEventArgs e is incorrect and will never compile if correctly bound to the TextChanged event.
The KeyEventArgs parameter is used by the KeyUp and KeyDown events. If you use these events, you will be looking to count every time the space bar is pressed and not the number of spaces in the text box. And like their name suggests, the events are raised every time a Key on the keyboard goes Up (Pressed) and Down (Released).

Cycling through multiple strings c#

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];
}
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.

Object reference not set to an instance of an object error using a for loop

private void btnAddStudent_Click(object sender, EventArgs e)
{
student[counter] = new Student(txtStudentName.Text, txtStudentSurname.Text, int.Parse(txtExamMark.Text), counter);
counter++;
}
private void btnAverage_Click(object sender, EventArgs e)
{
for (int i = counter; i <= counter; i++)
MessageBox.Show("" + student[i].Average);
}
My program is giving me the error:
Object reference not set to an instance of an object.
I only want the loop to run once to only display the last calculated average. If i do this:
ie: change int i = counter to i = 0
private void btnAverage_Click(object sender, EventArgs e)
{
for (int i = 0; i < counter; i++)
MessageBox.Show("" + student[i].Average);
}
Then my program works but it displays the messagebox as many times depending on the amount of students i entered, with the last value being the correct average.
I used a class called Student to calculate the average. That is not the problem however, because the correct average is being displayed.
What can I do to fix this error?
Firstly, you do not appear to need a loop since counter is going from counter to counter.
Secondly, I suspect you have an out-by-one error.
What happens if you try this?
private void btnAverage_Click(object sender, EventArgs e)
{
if (counter > 0)
MessageBox.Show("" + student[counter-1].Average);
}
Your problem is that student[counter] is null, while student[0] isn't, so I guess that your counter is not properly aligned with your student array.
Try
if (student.Length > 0)
{
MessageBox.Show("" + student[student.Length - 1].Average)
}
without the loop - that will just show the last average in the array.
I believe the problem is because you are trying to access an item in the array/collection that has no instance (Why you receive the error). Setting counter to 0 works because student[0] has an instance of Student.
If you want to only get one item, you don't need a loop, you can access student[i] directly by passing in the index of the array, i.e. 0.
MessageBox.Show("" + student[0].Average);
A less error-prone approach would be to use a List<T> instead of an array:
List<Student> students = new List<Student>();
private void btnAddStudent_Click(object sender, EventArgs e)
{
students.Add(Student(txtStudentName.Text, txtStudentSurname.Text,
int.Parse(txtExamMark.Text), counter);
counter++;
}
private void btnAverage_Click(object sender, EventArgs e)
{
if(students.Any())
{
MessageBox.Show("" + students.Last().Average);
}
}

Categories