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
Related
I'm a beginner, I'm making a form to analyze keywords like "key, form, text, array" into TextBox1 and see the number of keywords I have entered but count it when there is a comma in front of it, the result appears in TextBox2 and it works
private void button1_Click(object sender, EventArgs e)
{
String count = "Keyword";
count1= textBox1.Text.Length - textBox1.Text.Replace(",", "").Length;
textBox2.Text=count1.ToString();
textBox4.Text = count;
if (count1 > 50)
{
textBox3.ForeColor = Color.DarkRed;
textBox3.Text = "Your keyword is more than 50!";
}
else
{
textBox3.Text = string.Empty;
}
}
Now I'm confused how to analyze the same keyword in Textbox1, it's very boring when I have to research them one by one, for example "key, form, text, key" there are 2 words "key" in that TextBox1, and I want to display that word in TextBox2
First of all, thank you for sharing your knowledge
If I understand correctly, you want to analyze how many "keywords" there are in your textbox separated by commas.
For this you can use the Split() method, which is assigned to any string type, with the separation parameter a comma (e.g. textBox.Split(',')).
The method will return a string array, where each element of the array is a string of your text, but separated by the comma now.
With a for loop you can step through this string array and count how many of these strings are one of your keywords that you are evaluating.
Hope this helps :)
In the following code, I'm doing a search as soon as the seventh character is entered. Everything is working fine except that the user cannot type spaces because, as expected they are getting removed every time a new character is entered since I'm calling the Trim() method on PropertyChangedevent. What I would like to be able to do is give the user the ability to type spaces but remove any leading and trailing spaces. In other words, if the user enters some spaces before and after the word or sentence he/she is searching for I want to remove the spaces and just search for the word.
For instance if the user types...
<space><space><space>The Cat<space><space><space>
I want the program to ignore the spaces and search for The Cat as soon as the last t is entered.
What would be the best way to accomplish this?
XAML:
<TextBox x:Name="myTextBox" Text="{Binding InputFileNameChanged, UpdateSourceTrigger=PropertyChanged}"/>
ViewModel .CS
public string InputFileNameChanged
{
get { return _inputFileName; }
set {
_inputFileName = value.Trim();
if (_inputFileName.Length == 7) {
// search file
}
}
}
If I were you, I'd not trim the backing field, and instead only trim before conducting the check/search. i.e.
public string InputFileNameChanged
{
get { return _inputFileName; }
set {
_inputFileName = value;
var trimmed = value.Trim();
if (trimmed.Length >= 7) {
// search file using trimmed
}
}
}
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.
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.
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.