Link to home
Start Free TrialLog in
Avatar of jjacksn
jjacksn

asked on

Number only text box

I wish to create a textbox that only accepts numbers and decimals.  What is the best way to design this?  
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Avatar of gena17
gena17

Hi,

You can try NumericUpDown control.

Gena
using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;

class TextBoxDemo:Form
{
  public TextBoxDemo()
  {
    NumberBox n1=new NumberBox();
    n1.TabIndex=0;
    Button b1=new Button();
    n1.Location=new Point(10,10);
    b1.Location=new Point(n1.Left+n1.Width+20,10);
    b1.Size=new Size(150,24);
    b1.Text="Wanna Give me Focus";    
    this.Controls.Add(n1);
    this.Controls.Add(b1);
  }
  public static void Main()
  {
    Application.Run(new TextBoxDemo());
  }
}

class NumberBox:TextBox
{
  public NumberBox()
  {
    this.CausesValidation=true;
    this.Validating+=new CancelEventHandler(TextBox_Validation);
  }

  private void TextBox_Validation(object sender,CancelEventArgs ce)
  {
    try
    {
      int value=Int32.Parse(this.Text);
    }
    catch(Exception)
    {
      ce.Cancel=true;
      MessageBox.Show("Please Enter Numeric Value");
    }
  }
}



See this
http://www.c-sharpcorner.com/Language/VisualInterfaceInCSPSD.asp
I guess a Regular Expression Validator is the simplest one
ASKER CERTIFIED SOLUTION
Avatar of Mohammed Nasman
Mohammed Nasman
Flag of Palestine, State of image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This is a old question, which I already anwser for another member:
https://www.experts-exchange.com/questions/21261213/TextBox-with-numeric-input-only.html
Avatar of jjacksn

ASKER

hehe, that "other member" is me.  just wanted to see if there was a more .NET specific way to do it.  
Avatar of jjacksn

ASKER

Mohammed, what about the delete button?
jjacksn
Delete button should work fine without problem, because I use KeyPress Event, I added (ascii = 8) for backspace button, so it should work fine too

Avatar of jjacksn

ASKER

Isn't delete a different ascii code than backspace?
yes

KeyPress event use Ascii code for the keys, therefore it can't see the Delete button, because that I add only Backspace(ASCII =8)

if you would like to override the Delete button, you have to use KeyDown or KeyUp and use the Keycode of the keys instead of ASCII

Hope it's more clear now

Regards,
Mohammed