[英]How to write simple ErrorMessage function
我試圖理解如何編寫簡單的錯誤消息函數,如果在文本框中輸入字符串而不是數字,該函數會做出反應。
假設我要計算值1和值2,但是如果輸入了字符串,則會在標簽中顯示錯誤。
例
1 +1 = 2
a + 1 =錯誤
我的密碼
Calculate.cs
public static string ErrorMessage()
{
string msg = "";
try
{
//do sth
}
catch (Exception ex)
{
msg = "Wrong value";
}
return msg;
}
Calculator.asxc
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//calculate - works
}
catch
{
Error.Text = Calculate.ErrorMsg();
}
也嘗試過這樣的事情,但似乎沒有用:
Calculate.cs
public static bool ErrorMessage(string value1, string value2)
{
bool check = true;
string error;
if (value1 != "" && value2 != "")
{
check = true;
}
if (value1 =="" || value2 =="")
{
check = false;
error = "Error!";
}
return check;
}
Calculator.asxc
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//calculate - works
}
//
catch
{
bool res = false;
res = Calculate.ErrorMessage(textBox1.Text, textBox2.Text);
Error.Text = res.ToString();
}
我知道第二種方法不檢查數字,但是我只是在嘗試實現一些邏輯,看看ti是否有效..但沒有任何作用
我迷路了...請幫助
據我了解,您使用數字廣告會希望您的應用程序在用戶輸入字符串而不是數字時顯示錯誤消息。
您應該使用Int32.Parse()
或Int32.TryParse()
方法。 有關此處的Parse和TryParse的更多信息。
方法TryParse足夠好,因為如果無法將字符串解析為整數,它不會引發錯誤,而是返回false。
這是示例如何在您的類中使用此方法,更改Button1_Click方法,如下所示:
protected void Button1_Click(object sender, EventArgs e)
{
int a;
int b;
// Here we check if values are ok
if(Int32.TryParse(textBox1.Text, out a) && Int32.TryParse(textBox2.Text, b))
{
// Calculate works with A and B variables
// don't know whats here as you written (//calculate - works) only
}
// If the values of textBoxes are wrong display error message
else
{
Error.Text = "Error parsing value! Wrong values!";
}
}
如果需要使用ErrorMessage方法,則可以在此處更改ErrorMessage方法,但這比較復雜,第一個示例更簡單:
public static string ErrorMessage(string value1, string value2)
{
int a;
int b;
// If we have an error parsing (note the '!')
if(!Int32.TryParse(value1, out a) || !Int32.TryParse(value2, b))
{
return "Error parsing value! Wrong values!";
}
// If everything is ok
return null;
}
希望對您有所幫助,請詢問是否需要更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.