SIP: Key.Shift not getting detected - c#

I am trying to create a text box which accepts only alphabets and numbers, and discards all the special characters. I need this for entering a valid file name, without extension.
I am using the following code:
private void txtFName_KeyDown(object sender, KeyEventArgs e)
{
if (!(((e.Key >= Key.A) && (e.Key <= Key.Z)) || ((e.Key >= Key.D0) && (e.Key <= Key.D9)) || (e.Key == Key.Shift) || (e.Key == Key.Back)))
{
e.Handled = true;
MessageBox.Show("No Special Characters are Allowed!");
}
}
Unfortunately the "KeyPress" event is not there, so I figured out that this is the best way to achieve what I am doing.
The problem I am facing is:
As you can see in the code above, I have taken care of the "Shift" key press, but when I press the "Shift" key on the SIP, the "No Special Characters are Allowed" Message box pops up 3 times before I can key in an upper case alphabet!!! So this essentially prevents me from entering any Upper case characters.
Worse still, it is accepting all the characters !##$%^&*(). Probably because it is detecting these as numbers from 0-9. It looks that the key codes are being returned the same for 2 and #, 3 and # and so on. This is very strange behavior! And I can not even use the underscore key with the above technique.
Such behavior is obviously not acceptable in a professional App.
How can I create a text box which accepts only alphabets, numbers and underscore, and discards all other characters?
Also, is there a problem with the "Shift" key not getting detected?

If I understand your query, you want to validate your text box.
I would use regular expressions to do this:
using System.Text.RegularExpressions;
// Add chars which you don't want the user to be able to enter
private Regex regularExpression = new Regex(#"!##$%^&*().", RegexOptions.IgnoreCase);
// Your text changed event handler
private void txtInput_TextChanged(object sender, TextChangedEventArgs e)
{
// Replace the forbidden char with ""
txtInput.Text = regularExpression.Replace(txtInput.Text, "");
txtInput.SelectionStart = txtInput.Text.Length;
}
Hopefully this will work for you.

Related

Leave Event / Regex Implemented (Query about ignoring Textboxes if empty / null)

I'm new to C#, and finding some difficulties when trying to implement the 'ignore regex function when textbox is empty'.
As shown below, within Leave event I have made it so that the data submitted in the name textbox is of alphabetic characters, however, upon testing, the application still warns me that the textbox requires alphabetic characters even if the textbox is EMPTY / NULL.
What I would like is to maintain the same regex function, but I want the application to NOT warn me about the requirements if textboxes are left empty.
Many thanks in advance.
private void txtName_Leave(object sender, EventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(this.txtName.Text, "^[a-zA-Z ]"))
{
MessageBox.Show("This textbox accepts only alphabetical characters.", "Warning");
this.txtName.ResetText();
}
else if (txtName.Text.Trim() == string.Empty)
{
return;
}
}
What you need to use is ^[a-zA-Z]*$
^ Beginning of string
[a-zA-Z]* with the addition of the * it represents 0+ Alpha
characters
$ end of string

String checking with Regex

I have a textBox in my program that contains a string that has to meet a few requirements. I'm asking this question to figure out the best way to meet these requirements.
This string can't be NullOrEmpty and it must be completely composed of integers. The string can also contain spaces, which is my sticking point because spaces aren't integers.
This is what I'm working with (I'm aware that it may be a bit redundant at the moment):
//I test the string whenever the textBox loses focus
private void messageBox_LostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(TextBox.Text))
ButtonEnabled = true;
else if (Regex.IsMatch(TextBox.Text, #"^\d+$") == false)
{
//I think my problem is here, the second part of the if statement doesn't
//really seem to work because it accepts characters if there is a space
//in the string.
if (TextBox.Text.Contains(" ") && !Regex.IsMatch(TextBox.Text, #"^\d+$"))
ButtonEnabled = true;
else
{
MessageBox.Show("Illegal character in list.", "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
ButtonEnabled = false;
}
}
else
ButtonEnabled = true;
}
I got the Regex solution from this answer.
Question: How do I make it so that this textBox only accepts values like these:
"345 78" or "456"?
The regular expression seems simple enough. It could be something along the line of (with the specified constraints):
^([\s\d]+)?$
In your LostFocus handler, you could use something like this:
ButtonEnabled = Regex.IsMatch(TextBox.Text, #"^([\s\d]+)?$");
The button will be enabled if:
It's an empty string
It contains only digits and spaces
If you want a regular expression that will extract the numbers as well, you could change the pattern to:
^(\s*(?<number>\d+)\s*)*$
And use the number capture group.
Note that the first pattern will match strings that are composed of spaces only.

C# - Textbox with only letters and numbers

How can I limit my textbox to only accept numbers and letters?
It should not even allow spaces or anything like "!", "?", "/" and so on.
Only a-z, A-Z, 0-9
Tried this and it did not work at all
if (System.Text.RegularExpressions.Regex.IsMatch(#"^[a-zA-Z0-9\_]+", txtTag.Text))
{
txtTag.Text.Remove(txtTag.Text.Length - 1);
}
Not even sure if that txtTag.Text.Remove(txtTag.Text.Length - 1); should be there because it makes the application crash.
You don't need a regex for that:
textBox1.Text = string.Concat(textBox1.Text.Where(char.IsLetterOrDigit));
This will remove everything that is not a letter or digit, and can be placed in the TextChanged event. Basically, it gets the text, splits it into characters and only pick what is a letter or digit. After that, we can concatenate it back to a string.
Also, if you'd like to place the caret at the end of the textbox (because changing the text will reset its position to 0), you may also add textBox1.SelectionStart = textBox1.Text.Length + 1;
try this
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsLetter(e.KeyChar) && !char.IsControl(e.KeyChar)
&& !char.IsSeparator(e.KeyChar) && !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
My thought is you could alter the KeyPressed or TextChanged events for that control to check if the characters entered are numbers or letters. For example, to check the characters as they are added in the textbox you could do something like the following :
myTextbox.KeyPress += new KeyPressEventHandler(myTextbox_KeyPress);
void myTextbox_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar >= Keys.A && e.KeyChar <= Keys.Z)
// you can then modify the text box text here
First of all, check out this article for some information.
I think what you should do on the client side is to add the pattern attribute in the corresponding HTML.
<input type="text" name="foo" pattern="[a-zA-Z0-9_]" title="Please input only letters and numbers">

Using different lengthed masks gridmaskedcolumn

How would I have an input of a variable length in the gridmaskedcolumn.
For this instance the grid is a password which must have at least 4 characters but can be longer than 4 characters and those characters must be numbers only. Also the characters must not be displayed.
<telerik:GridMaskedColumn DataField="Pin" UniqueName="Pin" HeaderText="Pin" Visible="false" Mask="<0..9>" DisplayMask="******" >
</telerik:GridMaskedColumn>
I tried reading for solutions online but it seems there are no solutions regarding a variable lengthen input.
From what I have been reading, GridMaskedColumn is not designed for variable-length input and therefore passwords are not ideal for GridMaskedColumns.
An alternative would be to use a normal GridBoundColumn and set the column mode to password.
if (e.Item is GridDataItem && e.Item.IsInEditMode)
{
GridDataItem edititem = (GridDataItem)e.Item;
TextBox txtpwd = (TextBox)edititem["Pin"].Controls[0];
txtpwd.TextMode = TextBoxMode.Password;
txtpwd.Visible = true;
}

How to let the textbox drop strings started with an Arabic character (semi each other) as it does in capital and small characters in default language?

In textbox autocomplete properties when i entered a character like 'm' it dropped all strings start with 'm' or 'M' but when i write a character 'أ' (this is an Arabic character) it dropped only string start with 'أ' , I want when i typed 'أ' or 'ا' or 'إ' or 'آ' it drop all strings start with any character from those not the typed character only , in C# windows application I'm not using ASP.net
Any suggestions????
I am quite surprised to see that neither the text box control nor the auto complete string collection has a way to specify what defines string equality for the auto-complete mechanism. The only way I can think of to get the behavior that you want would be to create your own auto-complete mechanism.
I have done this several times in the past, before the functionality was supplied by the framework, and it is not difficult.
Just use an editable ComboBox instead of a TextBox, and handle the TextChanged event to create the autocompletions.
Here is some untried pseudocode of the procedure:
bool textChangedProgramatically = false;
List<string> myStrings; // The list of items that can appear in the auto-complete.
private static myComboBox_TextChanged(object sender, EventArgs args)
{
if (textChangedProgramatically)
return;
string searchText = myComboBox.Text;
// Use appropriate culturally-sensative string StartsWith comparisons
List<string> matchingItems = GetMatchingStrings(searchText, myStrings);
string firstMatch;
if (matchingItems.Length > 0)
firstMatch = matchingItems[0];
else
firstMatch = string.Empty;
myComboBox.Items.Clear;
myComboBox.Items.AddRange(matchingItems);
string fulltext = searchText;
if (firstMatch.Length > fullText.Length)
{
fullText = fullText + firstMatch.Substring(fullText.Length);
textChangeProgramatically = true;
myComboBox.Text = fullText;
myComboBox.SelectionStart = searchText.Length;
myComboBox.SelectionLength = fullText.Length - searchText.Length;
textChangeProgramatically = false;
}
}
The trick is to get the right matching behavior in GetMatchingStrings. You may want to use string compatibility normalization to get the Arabic characters into non-presentation forms before doing the comparison, but I expect the right SubString overload might handle all of these cases for you.

Categories