How to prevent the first character to be a number - c#

I have a textbox control and allowing the user to enter only letters or numbers:
private void tbTableName_TextChanged(object sender, EventArgs e)
{
tbTableName.Text = string.Concat(tbTableName.Text.Where(char.IsLetterOrDigit));
if (tbTableName.Text.Length > 0)
{
btnConvert.Enabled = true;
}
else
{
btnConvert.Enabled = false;
}
}
How can I modify so that the first character cannot be a digit, only letter and then they can add as many digit as they want?
I have a WinForm, not a Web Form.

You just need to modify this line:
if (tbTableName.Text.Length > 0)
to:
if (tbTableName.Text.Length > 0 && !Char.IsDigit(tbTableName.Text[0]))

Why not using regular expression?
I edit the regular expression to allow user to add digit or letter after the first digit
btnConvert.Enabled = System.Text.RegularExpressions.Regex.IsMatch(input, "^[a-zA-Z][a-zA-Z0-9 ]+$");

private void tbTableName_TextChanged(object sender, EventArgs e)
{
string name = Regex.Replace(tbTableName.Text, #"^\d+|\W", string.Empty);
btnConvert.Enabled = name.Length > 0;
tbTableName.Text = name;
}

You could just remove the first character if it's a number:
if (tbTableName.Text.Length > 0 && char.IsNumber(tbTableName.Text[0]))
tbTableName.Text = tbTableName.Text.Substring(1);

Related

Regex mask with replace for digits and only one hyphen C#

I saw a similar topic (this) but could not reach the ideal solution.
What I need:
A mask that works on the keypress event of aTextBox replacing non-numeric and excessive hyphens with "".
Allowing:
What is my difficulty?
Check for the entry of only one hyphen in the same expression.
I got into the solution using substring and it only worked in KeyUP, but I wanted to get through using an expression and keypress event.
What I've already tried:
using System.Text.RegularExpressions;
//trying to denie non-digit and hyphen.
//In conjunction with replace I remove everything that is not hyphen and digit
private static Regex MyMask = new Regex(#"[^\d-]");
private void inputSequential_KeyUp (object sender, KeyEventArgs e)
{
if (! String.IsNullOrEmpty (inputSequential.Text)
{
inputSequential.Text = MyMask.Replace (inputSequential.Text, "");
// MatchCollection matches = Regex.Matches (inputSequential.Text, "[\\ -]");
//
// if (matches.Count> 1)
// {
// for (int i = 1; i <= matches.Count - 1; i ++)
// {
// inputSequential.Text = inputSequential.Text.Substring (0, matches [i] .Index-1) + inputSequential.Text.Substring (matches [i] .Index, inputSequential.Text.Length);
// inputSequential.Text = inputSequential.Text.Replace (inputSequential.Text [matches [i] .Index] .ToString (), "");
//}
//}
}
}
Expected:
If you know better ways to do this please let me know.
Thanks for listening.
You can use a LINQ expression to get only the numbers and one hyphen:
string input = "12-3-47--Unwanted Text";
int hyphenCount = 0;
string output = new string(input.Where(ch => Char.IsNumber(ch) || (ch == '-' && hyphenCount++ < 1)).ToArray());
You seem at lost:
that expression: (:? ) - is not a nonmatched group. The correct variant is : (?: )
digitsOnly - it will be \d?
You should not escape -
If you are looking for a -, simply write it down.
For regex - Better write down in words, what are you looking for. For excluding or for taking in, does not matter, but SAY IN ENGLISH, what do you need.
Please, write down examples that should be accepted and these ones that should NOT be accepted.
For getting only numbers, possibly with - before, use:
-?\d+
tests
I searched here for some alternatives, with Regex or MaskedTextBox (This did not help me much because by default it is not supported in toolStrip where my textBox was).
At the end of the day the best solution I found was dealing with the input of values ​​to each char:
private void inputSequencial_KeyPress(object sender, KeyPressEventArgs e)
{
//Allow only digits(char 48 à 57), hyphen(char 45), backspace(char 8) and delete(char 127)
if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 45 || e.KeyChar == 8 || e.KeyChar == 127)
{
switch (e.KeyChar)
{
case (char)45:
int count = inputSequencial.Text.Split('-').Length - 1;
//If the first char is a hyphen or
//a hyphen already exists I reject the entry
if (inputSequencial.Text.Length == 0 || count > 0)
{
e.Handled = true;
}
break;
}
}
else
{
e.Handled = true; //Reject other entries
}
}
private void inputSequencial_KeyUp(object sender, KeyEventArgs e)
{
//if last char is a hyphen i replace it.
if (inputSequencial.Text.Length > 1)
{
string lastChar = inputSequencial.Text.Substring(inputSequencial.Text.Length - 1, 1);
if (lastChar == "-")
{
inputSequencial.Text.Replace("-", "");
}
}
}
You can use this for nondigit [^\d]:
var st = "1kljkj--2323'sdfkjasdf2";
var result = Regex.Replace(st, #"^(\d).*?(-)[^\d]*(\d+)[^\d]*", #"$1$2$3");
1-23232

how to display the number of letters in alphabet in label while typing in the textbox

I'm trying to make a program that whenever you type a letter in the textbox the number of the letter in alphabet would appear in the label......
I've tried some codes like this:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string userInput = textBox1.Text;
char charCount;
charCount = userInput[0];
label1 = charCount.Length.ToString();
}
But I can't find my solution for my problem.....
I'll appreciate the help I can get....
Show letter position in alphabet.
private void textBox1_TextChanged(object sender, EventArgs e)
{
string userInput = textBox1.Text; //get string from textbox
if(string.IsNullOrEmpty(userInput)) return; //return if string is empty
char c = char.ToUpper(userInput[userInput.Length - 1]); //get last char of string and normalize it to big letter
int alPos = c-'A'+1; //subtract from char first alphabet letter
label1 = alPos.ToString(); //print/show letter position in alphabet
}
First of all, you need to find an event, that is triggered, when you text in the textbox is changed. For example KeyUp. Then you need to register a function to it by using code like this.
your_textbox.KeyUp += your_textbox_KeyUp;
Visual Studio will help you by creating an empty function.
The function should look like this:
private void your_textbox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
your_label.Content = your_textbox.Text.Length.ToString();
}
your_label.Content is the Property that will be displayed in the label and the term on the right will get the length of the text in your textbox.
If you want the label not only to say the number, but wrap it in a text, use String.Format like this:
your_label.Content = String.Format("The text is {0} characters long", your_textbox.Text.Length);
My answer is aiming for WPF though. If you are using WinForms some keywords might be different.
I believe that you want only the number of letters (alphabet) written in the textbox, here's a simple code :
private void textbox_TextChanged(object sender, EventArgs e)
{
int i = 0;
foreach (char c in textbox.Text)
{
int ascii = (int)c;
if ((ascii >= 97 && <= 122) || (ascii >= 65 && ascii <= 90)) // a to z or A to Z
i++;
}
label1.Text = i.ToString();
}
More simple code :
private void textbox_TextChanged(object sender, EventArgs e)
{
int i = 0;
foreach (char c in textbox.Text)
if (char.IsLetter(c))
i++;
label1.Text = i.ToString();
}
If you're looking for the number of distinct letters in the textbox, you could use:
textbox.Text.ToUpper().Where(char.IsLetter).Distinct().Count();

How to use backspace which stops at the number 0

I am new to c# and I am trying to create a backspace button (for a calculator) that when pressed, can only backspace until the textbox has reached 0.
i don't know what else to add, so far I am at:
displaytxt.Text = displaytxt.Text.Substring(0, displaytxt.Text.Length - 1);
so far its able to backspace to " " then eventually crashes if used again.
i wish to limit the backspace button so if there's no more text entered in the field, it will automatically change the text to "0".
Answered, thanks guys :)
Use String.IsNullOrEmpty
private void backSpaceButton_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(displaytxt.Text))
{
displaytxt.Text = displaytxt.Text.Substring(0, displaytxt.Text.Length - 1);
}
}
You have to apply check before calling substring
if(string.Empty != displaytxt.Text)
displaytxt.Text = displaytxt.Text.Substring(0, displaytxt.Text.Length - 1);
or you can check the length
if(displaytxt.Text.Length > 0)
displaytxt.Text = displaytxt.Text.Substring(0, displaytxt.Text.Length - 1);
You say you want to never get an empty string, you want to get "0" if you backspace while you only have a single character left. So, check if you have a single-character string:
if (displaytxt.Text.Length == 1)
displaytxt.Text = "0";
else
displaytxt.Text = displaytxt.Text.Substring(0, displaytxt.Text.Length - 1);
Note: make sure you don't have any other code that sets displaytxt.Text to an empty string.
You can try this way :
displaytxt.Text = displaytxt.Text.Length > 1 ?
displaytxt.Text.Substring(0, displaytxt.Text.Length - 1) :
"0";
If you wnat to emulate BackSpace key you can do something like that:
private void backSpace_Click(object sender, EventArgs e) {
if (displaytxt.SelectionLength > 0)
displaytxt.Text = displaytxt.Text.Remove(displaytxt.SelectionStart, displaytxt.SelectionLength);
else if (displaytxt.SelectionStart > 0) {
int start = displaytxt.SelectionStart;
displaytxt.Text = displaytxt.Text.Remove(start - 1, 1);
displaytxt.Select(start - 1, 0);
}
}
If you want just to remove the last char you can achive it
private void backSpace_Click(object sender, EventArgs e) {
if (!String.IsNullOrEmpty(displaytxt.Text))
displaytxt.Text = displaytxt.Text.Remove(displaytxt.Text.Length - 1);
}

Get last entered word of RichEditControl

How do I get the last entered word in RichEditControl
here my code
private void richEditControl1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == ' ')
{
int wordEndPosition = richEditControl1.Document.CaretPosition.ToInt();
int currentPosition = wordEndPosition;
while (currentPosition > 0 && richEditControl1.Text[currentPosition - 1] != ' ')
{
currentPosition--;
}
string word = richEditControl1.Text.Substring(currentPosition, wordEndPosition - currentPosition);
this.Text = "Last char typed: " + word;
}
}
But when i press Enter create new line, it was wrong.
I guess you want to get a word whether it is surrounded by spaces or new lines, as long as it is the last one? Maybe you should include New Line check in your While loop, so it doesn't check just spaces.
richEditControl1.Text[currentPosition - 1] != "\n"
or something alike. Not sure if "\n" will pass , since I didn't work with such examples for some time. It probably just didn't know what to do whit new line.
Try:
public Form1()
{
InitializeComponent();
richEditControl1.KeyUp +=richEditControl1_Key;
}
private void richEditControl1_Key(object sender, KeyEventArgs e)
{
var currentText = richEditControl1.Text.Replace("\n", "");
currentText = richEditControl1.Text.Replace("\r", " ");
String result = currentText.Trim().Split(' ').LastOrDefault().Trim();
Console.WriteLine(String.Format("{0}| {1}", DateTime.Now.ToLongTimeString(), result));
}

Storing values from texbox into an array and then checking the length of input to match array size c#

I am new to C#. I have been trying to take values entered into a text box, on a windows form, and then save them in an array. I was trying to then get a message to be displayed if the input data was bigger than the size of the name.
e.g. A person enters their name into a textbox. The array might have a size of [20]. So if the name is longer than 20 characters, a warning will be displayed.
I have this which works but is not using the array to check input.
string[] name = new string[20];
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length <= 0)
{
MessageBox.Show("empty");
}
else if (textBox1.Text.Length > 20)
{
MessageBox.Show("Too many letters");
}
else
{
}
}
You can validate the TextBox if has string or empty with IsNullOrWhiteSpace if you're using Net 3.5 framework or later
char[] name;
private void button2_Click(object sender, EventArgs e)
{
int countChar = textBox1.Text.Trim().Count();
if (string.IsNullOrWhiteSpace(textBox1.Text)) //if (countChar == 0)
{
MessageBox.Show("empty");
return;
}
if (countChar > 20)
{
MessageBox.Show("You have entered " + countChar.ToString() + " letters, Too many letters");
return;
}
MessageBox.Show("Success");
}
EDIT: I realized that the OP want to store the TextBox values to array
var toArray = textBox1.Text.Trim().ToArray();
name = toArray.ToArray();
but is not using the array to check input.
It is using array internally. String is char[] and String.Length is actually Length of Char array.
string[] name = new string[20];
You donot need string[] to store a string of length 20.
For this task better use list:
List<String> list_string=new List<String>();
To add item You need:
list_string.Add("My String");
List is dynamic collection so you will never excced range.
Other way when you use String class.
String is char of array it is dynamic objec so You never excced range.
Change your name array to char[] instead of string[]. What you're saying here is that you have an array of strings; like 20 full names instead of 20 characters of a name.
In your if statement you can use the array and the textbox for your conditions
else if (textBox1.Text.Length > name.Length)
{
MessageBox.Show("Too many letters");
}
There are many other things wrong with this and could be done differently, but to focus on your question, I've left all other unrelated information out of this answer.
Do this:
// Global string list
List<string> inputList = new List<string>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length <= 0)
{
MessageBox.Show("empty");
}
else if (textBox1.Text.Length > 20)
{
MessageBox.Show("Too many letters");
}
else
{
// Add to list if less than 20 but greater than 0
inputList.Add(textBox1.Text);
}
}

Categories