[英]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.