In a C# 2010 desktop application, I want a textbox field to contain only letters in upper case. In addition, I want to allow for numbers. Any other values are not valid for this textbox field.
Thus can you show me code on how to setup the edit for uppercase letters and numbers only in the textbox?
Loading

VulpesRank #55 · 29.2K reputationPosted Jul 3, 2013, 8:56 AM EDT
Iftikar HussainRank #423 · 5.9K reputationPosted Jul 3, 2013, 8:57 AM EDT
You can do this by using Regular Expression
Valid - A123, ABC1, ABC111, ABC3783782, AOEIS292999
Invalid - abc, 123, abc123, Abc123
Regards,
Iftikar
dcRank #2,247 · 627 reputationPosted Jul 3, 2013, 12:15 PM EDT
How would yu change the code?
dcRank #2,247 · 627 reputationPosted Jul 3, 2013, 12:18 PM EDT
VulpesRank #55 · 29.2K reputationPosted Jul 3, 2013, 12:49 PM EDT
However, the easiest way to deal with this is to disable pasting altogether either from the context menu (by right clicking the TextBox) or from the keyboard by pressing either Control-V or Shift-Insert.
This can be done as follows:
public Form1()
{
InitializeComponent();
textBox1.ContextMenu = new ContextMenu(); // effectively disables context menu
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Control && e.KeyCode == Keys.V) || (e.Shift && e.KeyCode == Keys.Insert))
{
e.SuppressKeyPress = true;
}
}
Regarding Iftikar's approach (i.e. post entry validation), the regular expression is not quite right. It should be:
if (Regex.IsMatch(text, @"^[A-Z0-9]+$"))
If you want to allow the TextBox to be left blank, replace + with *
Iftikar HussainRank #423 · 5.9K reputationPosted Jul 3, 2013, 10:04 PM EDT
Regards,
Iftikar
dcRank #2,247 · 627 reputationPosted Jul 6, 2013, 1:03 PM EDT
dcRank #2,247 · 627 reputationPosted Jul 6, 2013, 1:09 PM EDT
Can you tell me where I can look to see what the various values of e.KeyCar means?
VulpesRank #55 · 29.2K reputationPosted Jul 6, 2013, 2:47 PM EDT
http://www.asciitable.com/
Iftikar HussainRank #423 · 5.9K reputationPosted Jul 6, 2013, 9:53 PM EDT
You can use Leave event of the textbox to check your input. It work for both copy paste and normal typing.
this.textBox1.Leave += new System.EventHandler(this.textBox1_TextLeave);
Regards,
Iftikar