Only numbers can be accepted in the text box, other characters do not process

xiaoxiao2021-03-06  69

Today, I replied to a similar post. This is also a question I just want to solve when I just learned C #. I wanted to write a "family small book", but how did I get it, I always judge in a keydown () event. Out of the input non-numeric characters, but can't stop the text box from accepting this input, non-numeric characters are still displayed.

First of all: I still repeat the question just now in VS2003.

1. Added a Windows Form Form1, adding a text box textBox12 in Form1, add the following code in the keydown () event of TextBox1: Private void textBox1_keydown (object sender, system.windows.forms.keyeventargs e) { IF (E.KeyValue <48 && E.KEYVALUE> 57) // If the input character is from '0' to '9' {// everything is} else {E.handled = true; // If you enter Non-digital characters, end this event in advance without adding MessageBox.Show (E.Handled.toString ());}}

Didn't finish it, you are going to do ...

Examples on MSDN http://msdn.microsoft.com/library/chs/default.asp?url=/library/chs/cpref/html/frlrfsystemWindowsFormsControlClassKeyDowntOPic.asp

[C #]

// boolean flag buy to determine WHEN a Character Other Than Number is entered.

Private bool nonnumbendered = false;

// Handle The Keydown Event to Dermine The Type of Character Entered Into The Control.

Private void textbox1_keydown (Object sender, system.windows.keyeventargs e)

{

// Initialize the flag to false.

Nonnumbendered = false;

// DETERMINE WHETHER THE Keystroke IS A Number from the top of the keyboard.

IF (E.KeyCode Keys.d9)

{

// DETERMINE WHETHER THESTROKE IS A Number from the keypad.

IF (E.Keycode Keys.Numpad9)

{

// determine WHETHER THE Keystroke IS A Backspace.

IF (E.Keycode! = Keys.back)

{

// a non-numeric Keystroke Was Pressed.

// set the flag to true and evatatern in keypress evenet.

Nonnumbendered = 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 E)

{

// Check for the flag being set in the keydown event.

IF (Nonnumbentered == True)

{

// stop the Character from Being Entered INTO The Control Since It Is Non-numeric.

e.handled = true;

}

}

转载请注明原文地址:https://www.9cbs.com/read-118943.html

New Post(0)