繁体   English   中英

C#邮费计算器

[英]C# postage calculator

我正在使用Windows Forms应用程序来开发邮资计算器-但是,我遇到了一些从int转换为string的问题。 该计算器旨在基于if-else语句,因此使用它们:)另外-如果textbox1中的权重值(g)小于或等于0,或大于2000,则它需要清除两个文本框。

我目前拥有的代码如下所示:

    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)
    {

    }

您也可以尝试将字符串转换为int,如下所示:

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.");
}

答案Selman22答案之间的区别在于,如果无法将字符串转换为int,则Convert.ToInt32将引发异常。 如果您已经在文本框中进行了验证,则可能没有必要。 但是,这些是在C#中将string转换为int的2种主要方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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