How create a numeric textbox

S

siedeveloper

Hi frnd,

Can u plz suggest me a way to create a numeric textbox?
Any suggestion or tip would be of great help.

with thanx.
 
M

Maarten Struys, eMVP

Derive a class from TextBox, override OnKeyPress, handle only numeric input
and ignore other input

for instance:

public class NumericTextBox : TextBox
{
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (Char.IsDigit(e.KeyChar))
{
base.OnKeyPress (e);
}
else // just eat the event in case of non digits
{
e.Handled = true;
}
}
}
 
J

JWW

In the KeyPress event you could try something like this:
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
e.Handled = !Char.IsDigit(e.KeyChar);
}
 
V

Vinay Chaudhari

Derive a class from TextBox, override OnKeyPress, handle only numeric
input and ignore other input

for instance:

public class NumericTextBox : TextBox
{
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (Char.IsDigit(e.KeyChar))
{
base.OnKeyPress (e);
}
else // just eat the event in case of non digits
{
e.Handled = true;
}
}
}

This is ofcourse 'the' way to go.... But you also have to allow for
other keystrokes as well e.g. backspace or +/- as a first character if
you want to support signed numbers.... and then one instance of decimal
point ('.') in case you want to have floating numbers.... and lets see
perhaps some other logic if you want to have exponent/matissa format...
and so on... I can only wish .NET Cf could have numeric textbox control
or maskedit for that matter... this list will also go on forever......

-Vinay.
 
M

Maarten Struys, eMVP

Of course, you are absolutely right. I could have mentioned that as well.
All I did was just give a pointer in the "right" direction. Since I didn't
have the need for a numeric textbox so far myself I couldn't my code yet,
because I don't have it at this time.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top