Click to See Complete Forum and Search --> : Numbers Only Textboxes!!


rocky_upadhaya
February 22nd, 2010, 08:34 AM
Hi! every one.
This time I have a problem on working with textboxes. What I have is 2 textboxes 1 for input of first integer type number(say a1) and and second for input of second is integer type number (say b1)...now I want to make sure that user can only type numbers in it.....
I have done some homework of my own but it does not check the space character and this method does not allow the use of tabs for shifting through the textboxes.......
Please Guide me in Here....Some hints for some would also be welcomed........

foamy
February 22nd, 2010, 08:57 AM
I can't remember where I originally got this, but it might be close to what you need:


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace Namespace
{
public class NumericTextBox : TextBox
{
bool allowSpace = false;

// Restricts the entry of characters to digits (including hex), the negative sign,
// the decimal point, and 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 are OK
}
else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) ||
keyInput.Equals(negativeSign))
{
// Decimal separator is OK
}
else if (e.KeyChar == '\b')
{
// Backspace key is OK
}
// else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0)
// {
// // Let the edit control handle control and alt key combinations
// }
else if (this.allowSpace && e.KeyChar == ' ')
{

}
else
{
// Consume this invalid key and beep
e.Handled = true;
// MessageBeep();
}
}

public int IntValue
{
get
{
return Int32.Parse(this.Text);
}
}

public decimal DecimalValue
{
get
{
return Decimal.Parse(this.Text);
}
}

public bool AllowSpace
{
set
{
this.allowSpace = value;
}

get
{
return this.allowSpace;
}
}
}

}

memeloo
February 22nd, 2010, 08:57 AM
this method does not allow the use of tabs for shifting through the textboxes
what kind of method?

have you tried to catch the KeyDown event?

rocky_upadhaya
February 22nd, 2010, 09:20 AM
I will look into the method that memelo gave...but for now I have somewhat a solution in this


try
{

if(Convert.ToInt32(a1.Text)==5)
//code
if(Convert.ToInt32(b1.Text)==6)
//code
}
catch(FormatException)
{
}


but can I know exactly which which statement generated the exception??

nelo
February 22nd, 2010, 10:41 AM
I will look into the method that memelo gave...but for now I have somewhat a solution in this


try
{

if(Convert.ToInt32(a1.Text)==5)
//code
if(Convert.ToInt32(b1.Text)==6)
//code
}
catch(FormatException)
{
}


but can I know exactly which which statement generated the exception??

Uhm...I don't think this a good solution to your problem. Why don't use the NumericTextBox that 'Foamy' posted? If you don't want to create a new control perhaps you can use a regular expression validator? That way the user get's some feedback and you wont' have to worry about invalid values...

memeloo
February 22nd, 2010, 10:41 AM
actually you should use the code @foamy posted. it exacly what you're looking for.

@foamy: I didn't know that the Char class has so cool methods like IsDigit. thx for posting it.

rocky_upadhaya
February 22nd, 2010, 10:47 AM
Thanks for the suggestion fells...now i will surely use the code example posted by the foamy...but I am not sure it will support tab to move through the textboxes.....but if it is possible I will update my work and its result....Thank you guys........

rliq
February 22nd, 2010, 10:39 PM
Alternatively, let them type anything they want but then validate it, either as textbox loses focus (can be painful) or when they clikc [OK] on the form (assuming that is an option).

rocky_upadhaya
February 22nd, 2010, 11:42 PM
any example or little insight on that? so that i can compare both the methode and evaluate which one suites me...coz i dont want to loose tab key navigation through textboxes...thanks

BigEd781
February 23rd, 2010, 01:52 AM
private void textBox1_KeyPress( object sender, KeyPressEventArgs e )
{
if( e.KeyChar == (char)Keys.Tab ) return;
e.Handled = !Char.IsDigit( e.KeyChar );
}


That is obviously a contrived example, it just shows how to keep tab working.

nelo
February 23rd, 2010, 02:56 AM
Alternatively, let them type anything they want but then validate it, either as textbox loses focus (can be painful) or when they clikc [OK] on the form (assuming that is an option).

A good suggestion. I would go for this option unless there was a specific requirement to validate as the data in entered.

rliq: I've just noticed .NET 4 in your location. how are you finding .NET 4? Are you using VS2010 or you just using the SDK? What about the new language features?

foamy
February 23rd, 2010, 04:04 AM
Um, tabbing works fine with the control I posted :)
(Just tested it to make sure)

Glad everyone likes it - I just wish the original author had put his/her name in the comments :-P

rliq
February 23rd, 2010, 04:26 PM
if you validate it at the 'end', when the user clicks [OK] you won't lose the tab functionality. Is there some reason why you have to evaluate after each character is typed, as that can start to complicate your code.

BigEd781
February 23rd, 2010, 05:19 PM
if you validate it at the 'end', when the user clicks [OK] you won't lose the tab functionality. Is there some reason why you have to evaluate after each character is typed, as that can start to complicate your code.

Why let users enter bad data to begin with? It is just annoying, and it is trivial to pass the Tab messages through the control. I would ask why anyone *would* validate at the end instead of up front.

rocky_upadhaya
February 24th, 2010, 04:23 AM
I am extreamly sorry for not mentioning that I was working on WPF and is the code given by foamy is not valid for WPF Applications?? because if comes with

Error 1 The type or namespace name 'KeyPressEventArgs' could not be found (are you missing
a using directive or an assembly reference?)

I am again sorry for my mistake...anyway this thread would help other guys......and I urge Moderators of this site to change shift this thread to WPF section.......

Arjay
February 25th, 2010, 01:27 PM
Rocky, a couple of things:

1) please remember to post WPF related items in the WPF forum.
2) when someone gives you code, try the code before asking other questions. For example, rather than speculating that the code won't work with TABS, you can load up the code and determine that yourself.

As far as moving the post..., I'm going to leave this post in this forum because the solution is a C# solution.

If you still need a WPF solution, please post another question in the WPF forum.

rocky_upadhaya
February 25th, 2010, 09:21 PM
Hi! Arjay, with regards
Thaks for the suggestion. IT was stupid of me not to remember that I was working on WPF...And not trying code given by foamy, was all my bad but i had seen the same code on 1 other site where many users complained that tab key was not working,so i posted my reply... but I Beg my pardon to foamy for complaining before trying out myself...
THANKS

Zaccheus
February 26th, 2010, 07:51 AM
Quick comment on Foamy's solution, that would still let people copy & paste invalid characters into the text box, wouldn't it?

foamy
March 5th, 2010, 02:43 AM
Quick comment on Foamy's solution, that would still let people copy & paste invalid characters into the text box, wouldn't it?

EDIT: I should test things properly before posting :)
It seems if you use the right click->insert method, you can insert invalid text to it ... I will have to take a look at that. Also, CTRL + V doesn't work


There we go:


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace Foamy
{
public class NumericTextBox : TextBox
{
bool allowSpace = false;
bool changing = false;

// Restricts the entry of characters to digits (including hex), the negative sign,
// the decimal point, and 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 are OK
}
else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) ||
keyInput.Equals(negativeSign))
{
// Decimal separator is OK
}
else if (e.KeyChar == '\b')
{
// Backspace key is OK
}
else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0)
{
// Let the edit control handle control and alt key combinations
}
else if (this.allowSpace && e.KeyChar == ' ')
{

}
else
{
// Consume this invalid key
e.Handled = true;
}
}

protected override void OnTextChanged(EventArgs e)
{
if (!changing)
{
changing = true;
//Check the text and make sure no invalid characters were pasted.
for (int i = this.Text.Length - 1; i >= 0; i--)
{
char c = this.Text[i];
if (!Char.IsDigit(c) && c != '\b' && !(this.allowSpace && c == ' '))
this.Text = this.Text.Remove(i, 1);
}
changing = false;
}
base.OnTextChanged(e);
}

public int IntValue
{
get
{
return Int32.Parse(this.Text);
}
}

public decimal DecimalValue
{
get
{
return Decimal.Parse(this.Text);
}
}

public bool AllowSpace
{
set
{
this.allowSpace = value;
}

get
{
return this.allowSpace;
}
}
}

}


Update: added base.OnTextChanged(e); to enable eventhandling by user :)

Ibzy
March 10th, 2010, 10:56 AM
This code by foamy is a work of art!
Following on from what someone else had suggested - how can I validate the text when [OK] is pressed in my form?
Sorry to ninja the thread, but I hope others would be wondering the same.

Thanks

mariocatch
March 10th, 2010, 11:10 AM
What sort of validation?

You can handle the OK button press event, and do conditional checks there. Perhaps a regex validator. Plenty of options.

rliq
March 10th, 2010, 09:52 PM
I still think vaildation is easier, either in response to the [Ok] button or when the Textbox loses focus.

However, it may be better to do it at key stroke time, but that can lead to much more complicated code. This case would surely be better written as a UserControl beased on the original TextBox control.

foamy
March 11th, 2010, 01:31 AM
This code by foamy is a work of art!
Following on from what someone else had suggested - how can I validate the text when [OK] is pressed in my form?
Sorry to ninja the thread, but I hope others would be wondering the same.

Thanks
Woah.. I can't take full credit for this. Although I wrote some of it, it's based on someone else's code. Probably from CodeProject.com, but I can't remember :D

I still think vaildation is easier, either in response to the [Ok] button or when the Textbox loses focus.

However, it may be better to do it at key stroke time, but that can lead to much more complicated code. This case would surely be better written as a UserControl beased on the original TextBox control.
Easier when starting from scratch maybe. But with this thing you can just drag it into the form and not have to worry.
I've never used UserControls, do you have an example of how this might work as one? It'd be a nice addition to the thread ^^