Only numeric value in textbox

  • Thread starter Thread starter Guest
  • Start date Start date
If you are only going to do this in one place then you can do something like
this:

private void textBox1_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)

{

e.Handled = !char.IsDigit(e.KeyChar);

}


Keep in mind the above code doesn't acct. for BackSpace, ., -, +, e

--
Thanks
Wayne Sepega
Jacksonville, Fl

Enterprise Library Configuration Console Module Generator
http://workspaces.gotdotnet.com/elccmg

"When a man sits with a pretty girl for an hour, it seems like a minute. But
let him sit on a hot stove for a minute and it's longer than any hour.
That's relativity." - Albert Einstein
 
The following code cam be used to validate the Text that has been input.
try
{
float myNumber = Float.Parse(txtBox1.text);
//Mynumber will have the value
}
catch
{
MessageBox.show("Invalid Number");
}
 
ZS said:
The following code cam be used to validate the Text that has been input.
try
{
float myNumber = Float.Parse(txtBox1.text);
//Mynumber will have the value
}
catch
{
MessageBox.show("Invalid Number");
}

IMO, it's better GUI design to not let the user input the invalid data in
the first place. Their ability to input invalid data could introduce
confusion.

This should work:

void tb_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != '\b';
}
 
I don't know if this helps, but I found a pertinent article on the Web (don't
remember where) which had the following two methods in it. I've implemented
them and they work great!


// Tests whether the input string is a whole number - ie. 0, 1, 2, ...
public static bool IsWholeNumber(string txt)
{
if (txt == null)
txt = "";

Regex objNotWholePattern=new Regex("[^0-9]");
return !objNotWholePattern.IsMatch(txt);
}


// Will return 'txt' as is if it's a number; otherwise will return a
null string
public static string NumericOnly(string txt)
{
if (IsWholeNumber(txt))
return txt;
else
return "";
}
 
Back
Top