簡體   English   中英

如果我在C#的文本框中以小數點開始輸入,則會出現輸入格式異常

[英]If I start input with decimal point in my textbox in C#, I get Input Format Exception

我正在以十進制計算織物重量。

如果輸入0.071,則程序運行正常。 但是,如果輸入.071,我會得到愚蠢的輸入格式異常錯誤。 我想刪除此令人討厭的輸入格式異常錯誤,因為用戶忘記輸入0.071。

這是詳細信息。

我的“織物重量”文本框的屏幕截圖,其中有小數點

  • 我的“織物重量”文本框的屏幕截圖,其中有小數點

我得到了例外。

  • 我得到了例外。

      try { if (System.Text.RegularExpressions.Regex.IsMatch(textBox28.Text, "[^0-9^+]")) { MessageBox.Show("Please enter only numbers."); textBox28.Clear(); textBox28.Focus(); } } catch (ArgumentOutOfRangeException err){ MessageBox.Show(err.ToString()); } try { // Input format error 702 FabricWeight = float.Parse(textBox28.Text); } catch (FormatException err) { MessageBox.Show(err.ToString()); 

FabricWeight = float.Parse(textBox28.Text); 您可以添加:

if(textBox28.Text.StartsWith('.')
{
      textBox28.Text = string.Format("{0}{1}", 0, textBox28.Text);
}

正如喬恩所說-使用TryParse效率更高。

在文本框的事件按鍵中嘗試以下代碼,它的更好方法是:

private void textBox28_KeyPress(object sender, KeyPressEventArgs e)
    {
        if ( System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[^0-9^+.]") )
            e.Handled = true;
        if (e.KeyChar == '.' && textBox28.Text.Length == 0)
            e.Handled = true;

        int i = 0;
        foreach (char cc in textBox28.Text)
            if (cc == '.')
                i++;
        if (i >= 1 && e.KeyChar == '.')
            e.Handled = true;
    }

我現在測試。 請檢查一下。

歸功於 @ Bruniasty

這可行。

“在此方法下面”我將結果存儲在“織物權重”中,您可以將其用於程序,並在“嘗試解析”之后存儲到所需的任何變量中。

    private static void TryToParse(string value)
    {
        double number;
        bool result = double.TryParse(value, out number);

        if (result)
        {

            FabricWeight = number;

        }
        else
        {
            if (value == null) value = "";

        }
    }

寫下並工作。

TryToParse(textBox28.Text);

有關更多信息:請訪問此鏈接MSDN庫:TryParse

暫無
暫無

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

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