i have textbox need allow numbers, delete , backsapce. code works this, allowing space key though disabled it. i'm not sure missing here.
public class numbertextbox : textbox { /// <summary> /// allows numbers, delete, backspace keys /// </summary> public numbertextbox() { keydown += new keyeventhandler(onkeydown); } private bool isnumberkey(key inkey) { if (inkey < key.d0 || inkey > key.d9) { if (inkey < key.numpad0 || inkey > key.numpad9) { return false; } } return true; } private bool isactionkey(key inkey) { return inkey == key.delete || inkey == key.back; } private bool isspacekey(key inkey) { if (inkey == key.space) { return true; } return false; } protected void onkeydown(object sender, keyeventargs e) { e.handled = !isnumberkey(e.key) && !isactionkey(e.key) && isspacekey(e.key); } }
from microsoft website:
public class numerictextbox : textbox { bool allowspace = false; // restricts entry of characters digits (including hex), negative sign, // decimal point, , editing keystrokes (backspace). protected override void onkeypress(keypresseventargs e) { base.onkeypress(e); numberformatinfo numberformatinfo = system.globalization.cultureinfo.currentculture.numberformat; string decimalseparator = numberformatinfo.numberdecimalseparator; string groupseparator = numberformatinfo.numbergroupseparator; string negativesign = numberformatinfo.negativesign; string keyinput = e.keychar.tostring(); if (char.isdigit(e.keychar)) { // digits ok } else if (keyinput.equals(decimalseparator) || keyinput.equals(groupseparator) || keyinput.equals(negativesign)) { // decimal separator ok } else if (e.keychar == '\b') { // backspace key ok } // else if ((modifierkeys & (keys.control | keys.alt)) != 0) // { // // let edit control handle control , alt key combinations // } else if (this.allowspace && e.keychar == ' ') { } else { // swallow invalid key , beep e.handled = true; // messagebeep(); } } public int intvalue { { return int32.parse(this.text); } } public decimal decimalvalue { { return decimal.parse(this.text); } } public bool allowspace { set { this.allowspace = value; } { return this.allowspace; } } }
Comments
Post a Comment