簡體   English   中英

限制文本框中的數字和字母-C#

[英]Restrict numbers and letters in textbox - C#

我想限制可以在文本框中輸入的數字和字母。 假設我只想允許數字0-5和字母ad(小寫和大寫)。 我已經嘗試過使用帶遮罩的文本框,但是它只允許我僅指定數字,僅指定字母(均無限制)或同時指定數字和字母,但順序相同。 最好的情況是:用戶嘗試輸入數字6,但沒有任何內容輸入文本框,對於af范圍以外的字母也是如此。 我認為最好使用的事件將是Keypress事件,但是我對如何實現限制事情一無所知。

為您的文本框使用KeyPress事件。

protected void myTextBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs)
{
    e.Handled = !IsValidCharacter(e.KeyChar);
}

private bool IsValidCharacter(char c)
{
    bool isValid = true;

    // put your logic here to define which characters are valid
    return isValid;
}
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;

// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Initialize the flag to false.
    nonNumberEntered = false;

    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
    {
        // Determine whether the keystroke is a number from the keypad.
        if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
        {
            // Determine whether the keystroke is a backspace.
            if(e.KeyCode != Keys.Back)
            {
                // A non-numerical keystroke was pressed.
                // Set the flag to true and evaluate in KeyPress event.
                nonNumberEntered = true;
            }
        }
    }
    //If shift key was pressed, it's not a number.
    if (Control.ModifierKeys == Keys.Shift) {
        nonNumberEntered = true;
    }
}

// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for the flag being set in the KeyDown event.
    if (nonNumberEntered == true)
    {
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;
    }
}

像這樣重寫PreviewKeyDownEvent:

    private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if (e.KeyCode == Keys.A || e.KeyCode == Keys.B || ...)
            e.IsInputKey = true;
        else
            e.IsInputKey = false;
    }

這將告訴textBox將其視為用戶輸入的鍵。

使用KeyDown事件,如果e.Key不在允許的范圍內,則只需e.Handled = true

一種替代方法是接受所有輸入,對其進行驗證,然后向用戶提供有用的反饋,例如,錯誤標簽要求用戶輸入一定范圍內的數據。 我更喜歡這種方法,因為用戶知道出了點問題並可以解決。 它在Web表單上的整個Web上使用,對於您的應用程序用戶來說一點也不奇怪。 按下一個鍵,根本沒有任何反應可能會造成混淆!

http://en.wikipedia.org/wiki/基本原理

Keypress事件可能是您最好的選擇。 如果輸入的字符不是您想要的字符,請在e.SuppressKey進行檢查,將e.SuppressKey設置為true ,以確保不會觸發KeyPress事件,並且該字符未添加到文本框中。

如果您使用的是ASP.NET Web窗體,則最容易進行正則表達式驗證。 在MVC中,像MaskedEdit這樣的jQuery庫將是一個不錯的起點。 上面的答案記錄了Windows窗體的處理方法。

暫無
暫無

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

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