Link to home
Start Free TrialLog in
Avatar of kranthi4uonly
kranthi4uonly

asked on

How to restrict user to enter first character as alphabet in textbox c# windows

How to restrict user to enter first character as alphabet in textbox in c# windows forms not asp.net
thanks
ASKER CERTIFIED SOLUTION
Avatar of crazyman
crazyman
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
you will need to wire the event up and also add

using System.Text.RegularExpressions;

plus  missed a } off the end
Avatar of pollock_d
pollock_d

you can catch the keypress event, check the key they typed, if it is a letter then simply consume it
public void OnKeyPress(KeyPressEventArgs e)        
{  
  string keyInput = e.KeyChar.ToString();
 
  if (!Char.IsDigit(e.KeyChar)) 
  { 
    e.Handled = true; // Swallow this invalid key
  }                                
}

Open in new window

You can use MaskedTextBox control.
See
http://msdn2.microsoft.com/en-us/library/kkx4h3az.aspx
poolock_d is a better solution, dont use winforms so much these days.


this will only check first character ad allow anything after that.



private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = ((sender as TextBox).Text.Length==0 && !Char.IsLetter(e.KeyChar));                                  
        }

Open in new window

the logic provided by poolock_d and crazyman is enough for simple strightforward entry case. but you need to handle other cases like
1. text already exists and user moves to this control and place the cursor at first character position, now alpha character should be valid.
2. text already exists and user moves to this control and selects first few characters and start entering new data,now alpha character should be valid.
there are many other ways to enter the data.

the better option is either to use validating event or textchanged event and validate the data.
Yeh the keydown has a few issues, copy & paste is another...