Truex
Truex

Reputation: 317

Trying to perform multiplication of three textboxes in Visual Studio

I am trying to perform a multiplication of three different values (three different textboxes). The code is added to button so when user clicks on it, it calculates all three values.

I have a code, when I debug it, it does not show any errors however it does not calculate and it won't show the result in textbox 'total'.

Here's the code:

private void button1_Click(object sender, EventArgs e)
    {
        Int32 val1 = Convert.ToInt32(amount.Text);
        Int32 val2 = Convert.ToInt32(length.Text);
        Int32 val3 = Convert.ToInt32(width.Text);
        Int32 val4 = val1 * val2 * val3;
        total.Text = Convert.ToString(val4);
    }

Thank you for your help in advance.

Upvotes: 1

Views: 113

Answers (2)

Alfie Goodacre
Alfie Goodacre

Reputation: 2793

There is no need to use the Int32 class, use int as it is much easier to read and more standardised.

This might also help with the arithmetic, which should be like this

int val1 = int.Parse(amount.Text);
int val2 = int.Parse(length.Text);
int val3 = int.Parse(width.Text);
int val4 = val1 * val2 * val3;
total.Text = val4.ToString();

This is assuming that the textBoxes may only have numbers input into them, if this is not the case then you can use TryParse instead.

int val1 = 0;
int val2 = 0;
int val3 = 0;
int val1 = if(!int.TryParse(amount.Text, out val1)) return; // could show MessageBox
int val2 = if(!int.TryParse(length.Text, out val2)) return; // could show MessageBox
int val3 = if(!int.TryParse(width.Text, out val3)) return; // could show MessageBox
int val4 = val1 * val2 * val3;
total.Text = val4.ToString();

Upvotes: 1

Rion Williams
Rion Williams

Reputation: 76547

You need to actually parse the string values within your TextBox Controls as integers so that you can perform your necessary operations with them.

Generally the safest approach is going to be to use the Int32.TryParse() method which will return a boolean indicating if the parse was successful and it will store the newly parsed value in a specified variable :

private void button1_Click(object sender, EventArgs e)
{
    // Define your variables
    int amount, length, width;

    if(!Int32.TryParse(amount.Text, out amount))
    {
         // Amount was not an integer, do something here
    }

    if(!Int32.TryParse(length.Text, out length))
    {
         // Length was not an integer, do something here
    }

    if(!Int32.TryParse(width.Text, out width))
    {
         // Width was not an integer, do something here
    }

    // At this point, you can calculate your result
    total.Text = Convert.ToString(length * width * amount);
}

Upvotes: 4

Related Questions