简体   繁体   中英

C# postage calculator

I am working on a postage calculater as a Windows Forms app - however I have encountered some problems converting from int to string - as I think it is. The calculator is meant to be based on if-else statements, hence the use of those :) Also - it needs to clear the two textboxes if the weight value (g) in textbox1 is less or equal to 0, or above 2000.

The code I have currently looks like this:

    private void button1_Click(object sender, EventArgs e)
    {
        int g;
        textBox1.Text = g.ToString();
        {
            if (g <= 0 || g > 2000)
            {
                Console.WriteLine("Your weight is either too low or too high");
                textBox1.Clear();
                textBox2.Clear();
            }
            else if (g > 0 && g <= 50)
            {
                textBox2.Text = ("9,00");
            }
            if (g > 50 && g <= 100)
            {
                textBox2.Text = ("18,00");
            }
            if (g > 100 && g <= 250)
            {
                textBox2.Text = ("28,00");
            }
            if (g > 250 && g <= 500)
            {
                textBox2.Text = ("38,50");
            }
            if (g > 500 && g <= 1000)
            {
                textBox2.Text = ("49,00");
            }
            if (g > 1000 && g <= 2000)
            {
                textBox2.Text = ("60,00");
            }
        }
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

You could also try converting a string to an int like this:

int g;
if (int.TryParse(textBox1.Text, out g))
{
    if (g <= 0 || g > 2000)
    {
        Console.WriteLine("Your weight is either too low or too high");
        textBox1.Clear();
        textBox2.Clear();
    }
    else if  ...
}
else // text box value could not be converted to an integer
{
    Console.WriteLine("You did not enter a valid number for weight.");
}

The difference between this and Selman22's answer is that Convert.ToInt32 will throw an exception if the string can't be converted to an int. If you already do validation on the text box, this may not be necessary. However these ARE the 2 main ways of converting a string to an int in C#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM