0

This code works fine only if I comment out the MessageBox.Show().

private void textBox1_KeyDown( object sender, KeyEventArgs e ) {
    if( textBox1.Text.Contains('.') && ( e.KeyCode == Keys.Decimal || e.KeyCode == Keys.OemPeriod ) ) {
        MessageBox.Show("More than one decimal point!");
        e.SuppressKeyPress = true;
    }
}

What is the reason? and How can I alert the User?

EDIT

Then How can I alert for the wrong Key Press?

kame
  • 20,848
  • 33
  • 104
  • 159
Naveen Kumar V
  • 2,559
  • 2
  • 29
  • 43

2 Answers2

1

You should try this

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if(textBox1.Text.Contains('.') && e.KeyChar == '.')
    {
        e.Handled = true;
        MessageBox.Show("More than one decimal point!");
    }
}

It would better work on KeyPress Instead of KeyDown

While discovering I got a wonderful page saying about the difference between the KeyDown and KeyPress events in .net

Community
  • 1
  • 1
Mohit S
  • 13,723
  • 6
  • 34
  • 69
  • 1
    `Suppress` is better than `Handled`: http://stackoverflow.com/questions/7557442/keyeventargs-handled-vs-keyeventargs-supresskeypress – Shaharyar Oct 07 '15 at 07:08
  • 1
    @Shaharyar: we wont get Suppress in KeyPress and thus need to use Handled – Mohit S Oct 07 '15 at 07:10
0

When you show message box, it leaves the focus from TextBox, and your code e.SuppressKeyPress = true doesn't execute at that time.

You should place your MessageBox after handling the input.

e.SuppressKeyPress = true;
MessageBox.Show("More than one decimal point!");
Shaharyar
  • 12,254
  • 4
  • 46
  • 66