on key press textbox not working properly - c#

if i enter 10 digits first time it takes 10 digits but if i clear textbox1 using backspace and enter again it takes only 9 digits. it should take 10 digits because i have set textbox1.maxlength=9 means it should count 10 digits(0 to 9).
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b' && textBox1.Text.Trim().Length > 9)
{
e.Handled = true;
MessageBox.Show("You can't enter more than ten digits...");
textBox1.MaxLength = 9;
}
}

MaxLength is the literal amount of characters, i.e. a MaxLength of 9 has an index ranging from 0-8. Set MaxLength to 10.

MaxLength is used for counting the literal amount of characters within a string, therefore setting MaxLength to 9, would count 0-8, as 0 counts as a literal character.
Your solution would be to set MaxLength to 10.

Related

Validating ID Number C#

I am working on this method that validates a student Id number. The credentials of the ID number are; the first character has to be 9, the second character has to be a 0, there can not be any letters, and the number must be 9 characters long. The method will return true if the student id is valid. When I go to test the method manually through main it comes out as true, even when I put in a wrong input. In my code, I have the if statements nested, but I originally did not have them nested. What is a better way to validate the input to align with the credentials of the ID number? Would converting the string into an array be more ideal?
public static bool ValidateStudentId(string stdntId)
{
string compare = "123456789";
if (stdntId.StartsWith("8"))
{
if (stdntId.StartsWith("91"))
{
if (Regex.IsMatch(stdntId, #"^[a-zA-Z]+$"))
{
if (stdntId.Length > compare.Length)
{
if (stdntId.Length < compare.Length)
{
return false;
}
}
}
}
}
You can try regular expressions:
public static bool ValidateStudentId(string stdntId) => stdntId != null &&
Regex.IsMatch(stdntId, "^90[0-9]{7}$");
Pattern explained:
^ - anchor - string start
90 - digits 9 and 0
[0-9]{7} - exactly 7 digits (each in [0..9] range)
$ - anchor - string end
So we have 9 digits in total (90 prefix - 2 digits + 7 arbitrary digits), starting from 90

Set minimum characters limit per line in asp.net using c#

I want to set the limit min. 5 characters per line and
I want to show message if multiline textbox have less than 5 chars. line.
Here is my code.
string[] temp = Regex.Split(KeywordList.Text, "\r\n");
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].Length <= 4) //check characters limit
{
Response.Write("Please enter min 5 characters per line");
}
else
{
Response.Write("success");
}
}
My textbox contains min. 5 characters in few lines but above code show "success".
Can anyone help me to detect less than 5 characters row.
Thanks in advance, sorry for my bad English.
I suggest using Linq: Split the initial string (please, do not put magic values like "\r\n", but Environment.NewLine) and check if Any item is 4 characters or less:
if (KeywordList
.Text
.Split(new string[] {Environment.NewLine}, StringSplitOptions.None)
.Any(item => item.Length <= 4))
Response.Write("Please enter min 5 characters per line");
else
Response.Write("success");
In your current code Regex.Split is an overshoot (String.Split is enough), and it seems that you should add break after Response.Write("Please enter min 5 characters per line"); line:
...
if (temp[i].Length <= 4) //check characters limit
{
Response.Write("Please enter min 5 characters per line");
break; // <- we have an error, no need to check more lines
}
...
Edit: If you are not sure in delimiters (they can be \n - Unix, \r\n - Windows, \n\r - Mac etc.) you can try several ones in one call
if (KeywordList
.Text
.Split(new char[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries)
.Any(item => item.Length <= 4))
Response.Write("Please enter min 5 characters per line");
else
Response.Write("success");
However, we have to eliminate empty items: for "a\r\n\b" we want ["a", "b"], not ["a", "", "b"]

String validations c#

I have a 9 character string I am trying to provide multiple checks on. I want to first check if the first 1 - 7 characters are numbers and then say for example the first 3 characters are numbers how would I check the 5th character for a letter range of G through T.
I am using c# and have tried this so far...
string checkString = "123H56789";
Regex charactorSet = new Regex("[G-T]");
Match matchSetOne = charactorSetOne.Match(checkString, 3);
if (Char.IsNumber(checkString[0]) && Char.IsNumber(checkString[1]) && Char.IsNumber(checkString[2]))
{
if (matchSetOne.Success)
{
Console.WriteLine("3th char is a letter");
}
}
But am not sure if this is the best way to handle the validations.
UPDATE:
The digits can be 0 - 9, but can concatenate from one number to seven. Like this "12345T789" or "1R3456789" etc.
It'a easy with LINQ:
check if the first 1 - 7 characters are numbers :
var condition1 = input.Take(7).All(c => Char.IsDigit(c));
check the 5th character for a letter range of G through T
var condition2 = input.ElementAt(4) >= 'G' && input.ElementAt(4) <= 'T';
As it is, both conditions can't be true at the same time (if the first 7 chars are digits, then the 5th char can't be a letter).

How can I fix c# masked textbox right-to-left input behaviour?

I use WinForms masked textbox to input time in the format of hh:mm:ss. My mask for this is 99:99:99, and I use right-to-left input mode.
The problem is, when I type 123 into it, I expect it to input 1:23, but it does this instead: __:12:3_ (so the value is 12:3x, and it replaces x with the next value that is typed).
What can I do to make it just push text to the left instead of copying the whole ss block to mm?
Edit: Here's a clarification:
My client needs to input time values in such a way that when he types:
12[Enter] it is accepted as 12 seconds
123[Enter] is 1 minute, 23 seconds
1234[Enter] would be 12 minutes, 34 seconds
12345[Enter] would be 1 hour, 23 minutes, 45 seconds, and so on...
The problem is that when 123 is typed into a masked textbox, it moves 12 to the minutes field, instead of just the 1, and only the 3 is left inside the seconds field.
Edit 2: As anyone who has worked with the masked textbox knows, setting the TextAlign to Right doesn't work the way you'd expect it to, like in any normal text editor. Instead, it just places the whole mask on the right side of the control, but the values are still inserted the same way as when the TextAligh is Left.
This is why I tried using RightToLeft.
What you want seems to be near impossible. How will the maskedtextbox know if you mean 1 digit to or 2 digits to apply to the first field that you type, unless you type the colon to show the separation?
I think for what you seem to want aDateTimePicker with a custom format of hh:mm:ss would work better. The input automatically starts at the hours field. The user can type 1 digit or 2 digits and then the colon and the input will automatically move to the next field. You also have the option of UpDown buttons that the user can click on to change the highlighted field.
By near impossible, I meant with native behavior. By creating a custom textbox that inherits from textbox you can do what you want:
public class TimeTextBox : TextBox
{
public TimeTextBox()
{
this.KeyPress += TimeTextBox_KeyPress;
}
public DateTime timeValue = new DateTime();
private void TimeTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
if(char.IsDigit(e.KeyChar))
{
Text += e.KeyChar;
SelectionStart = Text.Length;
}
else
{
MessageBox.Show("Wrong input");
return;
}
FixText();
if(Text.Length > 3 && !DateTime.TryParse(Text, out timeValue))
{
MessageBox.Show("Wrong input");
Text = Text.Remove(Text.Length - 1);
FixText();
timeValue = DateTime.Parse(Text);
}
}
private void FixText()
{
Text = Text.Replace(":", "");
for(int i = Text.Length - 3; i > -1; i -= 2)
{
Text = Text.Insert(i + 1, ":");
SelectionStart = Text.Length;
}
}
}
This will format and validate the input always counting from the right and inserting colons every 2 characters. There's simple validation, but it hasn't been tested for all scenarios.
You can use a simple text box and break the string as per this logic. I have only shown you for minutes and seconds you can extend it to hours following the code.
int seconds, minutes;
if (textBox1.Text.Length == 1 || textBox1.Text.Length == 2)
{
seconds = int.Parse(textBox1.Text);
}
else if (textBox1.Text.Length == 3)
{
seconds = int.Parse(textBox1.Text.Substring(1, 2));
minutes = int.Parse(textBox1.Text.Substring(0, 1));
}
else if (textbox1.Text.Length == 4)
{
seconds = int.Parse(textBox1.Text.Substring(2, 2));
minutes = int.Parse(textBox1.Text.Substring(0, 2));
}

Max Character Per line in a textbox in C#

I have a textbox and i want that it should have only 21 characters at max and they should be displayed in 3 lines(7 characters in each). As the user is typing when he types the 7th character i want the focus to be shifted to next line. I have already tried the following code
int textLength = a.Text.Length;
if (textLength % 8 == 0)
{
a.Text += "\n";
a.SelectionStart = a.Text.Length - 1;
}
It does not work .
Thanks for the help.

Categories

Resources