簡體   English   中英

C# - TextBox驗證

[英]C# - TextBox Validation

我有一些代碼檢查並確保當用戶在字段中輸入時必須輸入1到10的整數。

雖然如果用戶關注該字段,那么“壞”數據(例如“fdgfdg”)仍然留在該字段中。 因此,有些人可以演示當焦點在場上丟失時,如果數據無效,則輸入默認值,例如5

private void textBox4_TextChanged(object sender, EventArgs e)
        {
            try
            {
                int numberEntered = int.Parse(textBox4.Text);
                if (numberEntered < 1 || numberEntered > 10)
                {
                    MessageBox.Show("You must enter a number between 1 and 10");
                }
            }
            catch (FormatException)
            {

                MessageBox.Show("You need to enter an integer");
            }
        }

你可以在這里使用幾個事件, LeaveLostFocusValidating這里有關於MSDN上這些不同事件的更多討論。

在某些情況下, LeaveLostFocus不會觸發,因此在您的情況下最好使用的是Validating事件:

    textBox1.Validating += new CancelEventHandler(textBox1_Validating);


    void textBox1_Validating(object sender, CancelEventArgs e)
    {
        int numberEntered;

        if (int.TryParse(textBox1.Text, out numberEntered))
        {
            if  (numberEntered < 1 || numberEntered > 10) 
            { 
                MessageBox.Show("You have to enter a number between 1 and 10");
                textBox1.Text = 5.ToString();
            }
        }
        else
        {
            MessageBox.Show("You need to enter an integer");
            textBox1.Text = 5.ToString();
        }
    }

看看這里 ,我會使用TryParse

如果您像在這里一樣進行手動滾動驗證,那么您需要做的就是在MessageBox.Show()之后設置默認值

在標准winforms中,我認為你沒有任何框架支持驗證,但你可以看看這個: http//msdn.microsoft.com/en-us/library/ms951078.aspx的靈感,所以你不要分散整個應用程序的這個邏輯

使用文本框控件上的Leave事件來驗證並設置默認值

暫無
暫無

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

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