Control textbox, promtly  
Author Message
ivanFSR





PostPosted: Windows Forms General, Control textbox, promtly Top

How I can limit textbox control

So, when I must input decimal number, but, if I make mistake and input text or integer, system must alert me that I can input onli decimals numbers. I know for maskedtextbox. Dou you have another choice.

Please help me and thx.




Windows Forms9  
 
 
SvenC





PostPosted: Windows Forms General, Control textbox, promtly Top

Check this thread: http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=945259&SiteID=1

--
SvenC


 
 
David L





PostPosted: Windows Forms General, Control textbox, promtly Top

Well, a MaskedTextBox would really do the trick.

However, if you don't want to use that, you could validate the user input with a regular expression for example when the control leaves focus. Something like the following:

private void textBox1_Leave(object sender, EventArgs e)

{

if (!Regex.IsMatch(textBox1.Text, @"\d[.,]\d"))

{

MessageBox.Show("Invalid!");

}

}

This would show a messagebox if the text in textBox1 doesnt contain [numerical value] , or . [numerical value]. In other words a decimal number (allowing both . and , due to cultural differences).


 
 
ivanFSR





PostPosted: Windows Forms General, Control textbox, promtly Top

Thx you SvenC but it's very complexly for me, I am beginner. So I need something what I can use very fast, and very simple.

 
 
boban.s





PostPosted: Windows Forms General, Control textbox, promtly Top

NumericUpDown is also a good choice.

 
 
ahmedilyas





PostPosted: Windows Forms General, Control textbox, promtly Top

one other way would be to implement a textbox keypress event, then check to see if the key pressed is a number, if it isnt, handle the event (cancel imput)

 

private void textbox1_keypress(object sender, KeyPressEventArgs e)

{

   if (!Char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))

   {

      e.Handled = true;

      MessageBox.Show("Only numeric input please!");

   }

}

 

this will allow you to also use the backspace/delete keys. It's also cheaper than regex which is a key