簡體   English   中英

退出應用程序后,類型為'System.FormatException'的未處理異常

[英]An unhandled exception of type 'System.FormatException' after exiting the app

 if (int.Parse(q.textBoxNumberOfEmployees.Text) < 15)
        {
            Rect1.Fill = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
        }

場景:主窗口和子窗口,mainWindowButton打開子窗口,用戶輸入信息,當用戶輸入信息時,子窗口關閉,並在主窗口中相應地顯示一個矩形。 一切正常! 但是,當我單擊子窗口的“ x”以手動關閉窗口時,僅向我顯示此錯誤! 我在先前的問題中尋找了與我類似的答案,但是沒有一個確切的問題。

所有代碼都在MainWindowButton_ClickEvent中

用戶可能沒有在q.textBoxNumberOfEmployees輸入整數,因此您需要進行處理。

方法1

var numOfEmployees;

if (!int.TryParse(q.textBoxNumberOfEmployees.Text, out numOfEmployees))
{
    // What do you want to do? The user did not enter an integer.
}

// Proceed normally because user entered integer and it is stored in numOfEmployees

方法2

答案所示,僅允許用戶在文本框中輸入數字。 由於您在多個位置進行了檢查,因此我將為此創建一個用戶控件,以便僅允許數字。 然后在每個需要的地方使用該用戶控件。 取決於您要使用哪種方法。

為了回應我對您的OP所做的評論,我將嘗試為您寫出它,實際上使用起來非常簡單:

    try
    {
        if (int.Parse(q.textBoxNumberOfEmployees.Text) < 15)
        {
            Rect1.Fill = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
        }
    }
    catch(System.FormatException ex) //This code will be executed because a System.FormatException was thrown
    {
        //write the error message to the console (optional)
        Console.WriteLine(ex.Message);

        //You can write whatever code you'd like here to try and combat the error.
        //One possible approach is to just fill Rect1 regardless. Delete the
        //code below if you would not like the exception to fill Rect1
        //if this exception is thrown.

        Rect1.Fill = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM