Max Character Per line in a textbox in C# - 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.

Related

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).

on key press textbox not working properly

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.

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));
}

C# Char Array - assigning, changing, displaying

I am working through Joyce Farrell's Visual C#2012 on my own (this is not a homework assignment). I have been stuck on this for the past two days, and have yet to find an answer that I understand. I am looking for a simple program - nothing fancy as I probably haven't read that chapter yet. :-) The problem that I am having is when I am trying to show '' for a non-guessed or incorrectly guessed letter. If I assign '' it looks good for the first letter, but when the user enters a second guess, it changes the second guess to a '?'. Why is that? Any help would be really appreciated. Thank you.
static void Main(string[] args)
{
string[] mysteryWordList = { "green", "snowflake", "tree", "joy", "red", "gift", "frozen", "merry" };
string mysteryWord; // hidden word
char[] mysteryWordArray;
char letterGuessed;
char[] guessWordArray;
Random ranNumberGenerator = new Random(); // generate a random number, at least 0 but < 8
int randomNumber = ranNumberGenerator.Next(0, 8);
mysteryWord = mysteryWordList[randomNumber]; // select a word from list using random number
Console.WriteLine("The Mystery word is: " + mysteryWord); // print word for my validation
mysteryWordArray = mysteryWord.ToArray(); // put mystery word into array to compare against guessWord array
Console.Write("MysterywordArray is: ");
Console.WriteLine(mysteryWordArray);
guessWordArray = new char[mysteryWord.Length]; // assign length to user guess array
// write mystery word in *'s
for (int x = 0; x < mysteryWord.Length; ++x)
Console.Write("*");
//guessWordArray[x] += '%'; adds value and then does not work...
Console.WriteLine();
while (guessWordArray != mysteryWordArray)
{
Console.Write("\nPlease guess a letter: ");
letterGuessed = Convert.ToChar(Console.ReadLine());
for (int x = 0; x < mysteryWord.Length; ++x)// go through each letter in mystery word
{
if (letterGuessed == mysteryWordArray[x]) // if match do this
{
Console.WriteLine("Yes, the letter {0} is in the mystery word!", letterGuessed);
guessWordArray[x] += letterGuessed;
}
if (letterGuessed != mysteryWordArray[x] && guessWordArray[x] == default(char)) // if match do this
guessWordArray[x] += '*';
}
Console.Write("Mystery Word: ");
Console.WriteLine(guessWordArray);
}
}
The command guessWordArray[x] += letterGuessed; is wrong. It dosent add the letter to the array it actualy changes the Xth element in the array. For example if guesswordArray contains { 'a', 'b', 'c' }
guesswordArray[0] += 'a' translates to guessWordArray[2] = 'a' + 'a'. Character addition is done by converting a character to the ascii code then the result is converted to a character. That means 'a'== 97 'a'+'a' == 194' Then 194 is converted back to a weird character from the ascii table.
This two lines :
guessWordArray[x] += letterGuessed;
....
guessWordArray[x] += '*';
should be like this instead :
guessWordArray[x] = letterGuessed;
....
guessWordArray[x] = '*';
By this += operator, you are appending the char from user input to existing char saved in the array. That will produce special character which which won't be displayed well in console (that's why you saw sort of ? char). I think you need to just assign the input char and replace existing char by using = instead of +=
Characters are essentially integers in their most basic form. When you are attempting to add subsequent letters to your array you are using += which is adding characters together. The initial character '*' is ASCII code 42, so what's happening is when you select a new letter ('g' for example in "gift") you are adding 103 to to that 42, and the ASCII character with the value 145 is being stored in the array. That value is unable to be displayed properly by the console. You need to just use the assignment operator since you want to write the new character to the array at the current index.
guessWordArray[x] = letterGuessed;
guessWordArray[x] = '*';

Categories

Resources