[英]Conditional Statetment to test if user input is integer or decimal
我有一個用於確定矩形區域的應用程序。 用戶通過兩個文本字段輸入寬度和長度,並通過單擊按鈕顯示結果。 我希望用戶能夠輸入十進制或整數值。
前端 :
<div>
Enter Value 1: <asp:TextBox ID="length_txt" runat="server"></asp:TextBox><br />
Enter Value 2: <asp:TextBox ID="width_txt" runat="server"></asp:TextBox><br />
<asp:Button ID="button1" runat="server" Text="submit" onclick="button1_Click" /><br />
<asp:Label ID="area_lbl" runat="server"></asp:Label>
<br />
</div>
后端
protected void button1_Click(object sender, EventArgs e)
{
//area_lbl.Text = Convert.ToString(Convert.ToInt32(length_txt.Text) * Convert.ToInt32(width_txt.Text));
area_lbl.Text = Convert.ToString(Convert.ToDecimal(length_txt.Text) * Convert.ToDecimal(width_txt.Text));
}
...我的問題是,如何創建一個if語句來測試輸入框是否為整數或十進制值?
永遠不要在用戶輸入上使用Convert.To<SomePrimitiveTypeHere>
。
如果輸入無法轉換,則會出現異常。
.Net框架中的每個原始類型都有一個TryParse
方法-如果轉換成功,它將返回true
,否則返回false。
因此,您的代碼應如下所示:
protected void button1_Click(object sender, EventArgs e)
{
int intLength, intWidth;
Decimal decimalLength , decimalWidth;
if(int.TryParse(length_txt.Text, out intLength) && int.TryParse(width_txt.Text, out intWidth))
{
area_lbl.Text = (intLength * intWidth).ToString();
}
else if(Decimal.TryParse(length_txt.Text, out decimalLength) && Decimal.TryParse(width_txt.Text, out decimalWidth))
{
area_lbl.Text = (decimalLength * decimalWidth).ToString();
}
else
{
area_lbl.Text = "Invalid input!";
}
}
但是,正如NineBerry在他的評論中所寫,每個整數值都可以表示為Decimal,您可以忽略第一個條件,只需編寫以下內容:
if(Decimal.TryParse(length_txt.Text, out decimalLength) && Decimal.TryParse(width_txt.Text, out decimalWidth))
{
area_lbl.Text = (decimalLength * decimalWidth).ToString();
}
else
{
area_lbl.Text = "Invalid input!";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.