C#中设置textbox限制条件的方法
本文实例讲述了C#中设置textbox限制条件的方法,分享给大家供大家参考。具体实现方法如下:
#region设置数量等textbox控件样式及限制条件(具体调用的方法就是重写或直接调用ShieldNumberTextBoxOtherKeys函数)
///<summary> ///屏蔽数字textbox的其他字符串 ///</summary> ///<paramname="sender"></param> ///<paramname="e"></param> publicvirtualvoidtBoxNumbers_KeyDown(objectsender,KeyEventArgse) { e.SuppressKeyPress=true;
switch(e.KeyCode) { caseKeys.D0: caseKeys.D1: caseKeys.D2: caseKeys.D3: caseKeys.D4: caseKeys.D5: caseKeys.D6: caseKeys.D7: caseKeys.D8: caseKeys.D9: caseKeys.NumPad0: caseKeys.NumPad1: caseKeys.NumPad2: caseKeys.NumPad3: caseKeys.NumPad4: caseKeys.NumPad5: caseKeys.NumPad6: caseKeys.NumPad7: caseKeys.NumPad8: caseKeys.NumPad9: caseKeys.Back: caseKeys.OemPeriod: caseKeys.Delete: caseKeys.Decimal: e.SuppressKeyPress=false; break; default: break; } }
publicvirtualvoidtBoxNumbers_KeyPress(objectsender,KeyPressEventArgse) { TextBoxtBox=senderasTextBox; charc=e.KeyChar;
if(c.ToString().Equals(".")) { if(tBox.Text.Length<=0) e.Handled=true; //小数点不能在第一位 else { floatf; floatoldf; boolb1=false,b2=false; b1=float.TryParse(tBox.Text,outoldf); b2=float.TryParse(tBox.Text+e.KeyChar.ToString(),outf); if(b2==false) { if(b1==true) e.Handled=true; else e.Handled=false; } } } }
///<summary> ///屏蔽数字textbox的其他字符串 ///</summary> ///<paramname="tbox">要屏蔽的textbox</param> publicvirtualvoidShieldNumberTextBoxOtherKeys(TextBoxtbox) { tbox.ImeMode=ImeMode.Disable; tbox.KeyDown+=tBoxNumbers_KeyDown; tbox.KeyPress+=tBoxNumbers_KeyPress; }
#endregion