How create a numeric textbox

  • Thread starter Thread starter siedeveloper
  • Start date Start date
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.
 
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;
}
}
}
 
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);
}
 
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.
 
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.
 
Back
Top