2016-10-12 98 views
1

我試圖理解,如何編寫簡單的錯誤消息函數,如果字符串輸入的是文本框而不是數字,會發生什麼反應。如何編寫簡單的ErrorMessage函數

比方說,我想計算值1和值2,但如果輸入字符串顯示標籤中的錯誤。

1 + 1 = 2

一個+ 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 works..but沒什麼不

我迷路了......請幫助

回答

2

據我所知,您使用數字廣告希望您的應用程序顯示錯誤消息,如果用戶輸入字符串而不是數字。

您應該使用Int32.Parse()Int32.TryParse()方法。 有關更多信息ParseTryParse here。

方法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; 
} 

合這有助於問問你是否需要更多信息。

+0

是的,你是在什麼即時通訊嘗試做點... 但我如何在另一個webform中顯示void函數? 也... 函數ErrorMessage()假設檢查value1,value2的獲取集值... – aiden87

+0

編輯的第一個示例,並添加* ErrorMessage *示例如果您需要此功能。一探究竟。 –

+0

這個作品完美!將嘗試通過代碼並理解它。謝啦! – aiden87