Abdullah Hassan Abdullah Hassan - 1 month ago 6
C# Question

Can't add numbers using the void method

I'm trying to add 25 to stdNumber (anything typed in a text box) using a void method..

public void IncreaseStudents(int num)
{
int.Parse(textBox3.Text + num);
}

private void button1_Click(object sender, EventArgs e)
{
School s1 = new School();

s1._schlName = textBox1.Text;
s1._schLevel = textBox2.Text;
s1._stdNumber = int.Parse(textBox3.Text);

listBox1.Items.Add(s1._schlName);
listBox1.Items.Add(s1._schLevel);
listBox1.Items.Add(s1._stdNumber + IncreaseStudents(25)); //throws an error here


As you can see School is a class name, SchName and schLevel are objects and are using string, while stdNumber is using int.

I can't figure out how to add numbers using void. It worked with int in the method but I need to use void. Please help.

Answer

To make IncreaseStudents work the way you want, you need to change two things: You need to return a value, meaning it can't be void. And you need change the way you turn textBox3.Text into an integer. You don't parse the whole expression, textBox3.Text + num; num is a number already. All you need (or want) to parse is textBox3.Text, because it's a string. And we'll use a different way of parsing, so that if the text doesn't represent a number, it will fail politely instead of throwing an exception.

public int IncreaseStudents(int num)
{
    int n;
    if (int.TryParse(textBox3.Text, out n))
    {
         return n + num;
    }
    else
    {
         MessageBox.Show("Not a number: " + textBox3.Text);
         return num;
    }
}

Then this line of code should work fine -- unless s1._stdNumber is something weird that you can't add to.

listBox1.Items.Add(s1._stdNumber + IncreaseStudents(25));

But that's not the assignment. The assignment says you have to use void. So, another try:

public void IncreaseStudents(int num, out int result)
{
    int n;
    if (int.TryParse(textBox3.Text, out n))
    {
         result = n + num;
    }
    else
    {
         MessageBox.Show("Not a number: " + textBox3.Text);
         result = num;
    }
}

And call like this:

int result = 0;
IncreaseStudents(25, out result)

listBox1.Items.Add(s1._stdNumber + result);

Silly, but if your instructor wants that, that's what he wants.