Pages

Thursday, 23 August 2012

Make a numeric Text Box In VB.net and C#

hi...........
Most of the time we want to a text box which can only take numeric value such as textbox design for taking input of age and we know age must be a number.Textbox is a control which takes string values by default for change its functionality follow instruction....
Key events occur in the following order:
  1. KeyDown
  2. KeyPress
  3. KeyUp
To handle keyboard events only at the form level and not enable other controls to receive keyboard events, set the KeyPressEventArgs..::.Handled property in your form's KeyPress event-handling method to true. Certain keys, such as the TAB, RETURN, ESCAPE, and arrow keys are handled by controls automatically. To have these keys raise the KeyDown event, you must override the IsInputKey method in each control on your form. The code for the override of the IsInputKey would need to determine if one of the special keys is pressed and return a value of true.

VB.Net



Dim con As Boolean
    Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
        con = False
        If e.KeyCode < Keys.D0 Or e.KeyCode > Keys.D9 Then
            If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode > Keys.NumPad9 Then
                If e.KeyCode <> Keys.Back Then
                    con = True
                End If
            End If
        End If
    End Sub

    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If con = True Then
            e.Handled = True
        End If
    End Sub

C#


Boolean con;
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            con = false;
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    if (e.KeyCode != Keys.Back)
                    {
                        con = true;
                    }
                }
            }

        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (con == true)
            {
                e.Handled = true;
            }
        }
 

No comments:

Post a Comment