How can I set a MaxLength of a line in a RichTextBox? - c#

I wonder if there's anyway i can set a maximum number of characters for a line in a RichTextBox. I know I can set a general MaxLength for the whole Box, but not for the line itself.
I was thinking that the only solution, or at least a viable one, would be to select the line in a TextRange, count the chars and check if it's greater than the max number I manually set. Then, create a new line with:
myRichTextBox.AppendText(Environment.NewLine);
and also set the caret position to the end of the selection with something similar to that:
myRichTextBox.CaretPosition = myRichTextBox.Selection.End;
Would that be the best approach for my problem, or is there an simpler way to do that?

You could set up a keypress event, when triggered, validate the key and desired length and append the Environment.NewLine when you want.

This is a tricky one I think and his code can pretty much do the trick:
private void myRichTextBox_TextChanged(object sender, EventArgs e)
{
int maxLen = 10;
int CursorIndex = myRichTextBox.SelectionStart;
var text = myRichTextBox.Text;
int startIndex = text.Substring(0, CursorIndex).LastIndexOf("\n") + 1;
int endIndex = text.IndexOf("\n", CursorIndex, text.Length - CursorIndex);
// if (startIndex < 0) startIndex = 0;
if (endIndex < 0) endIndex = text.Length;
string line = text.Substring(startIndex, endIndex - startIndex).Trim();
if (line.Length > maxLen)
{
int insertionPoint = startIndex + maxLen;
text = text.Insert(insertionPoint, "\n");
CursorIndex += (insertionPoint < CursorIndex) ? 1 : 0;
myRichTextBox.Text = text;
myRichTextBox.SelectionStart = CursorIndex;
}
}
however I think there should be a better way to do this.

Related

Replace a character in specific position if line starts with condition C#

I am trying to modify a txt file, I need to change the 45 character with a P if the line starts with 8
for (int i = 0; i < textBox.Lines.Length; i++)//Loops through each line of text in RichTextBox
{
string text = textBox.Lines[i];
if ((text.Contains("8") == true)) //Checks if the line contains 8.
{
char replace = 'P';
int startindex = textBox.GetFirstCharIndexFromLine(i);
int endindex = text.Length;
textBox.Select(startindex, endindex);//Selects the text.
richTextBox1.Text = textBox.Text.Substring(0, textBox.SelectionStart) + (0, textBox.Lines) + replace + textBox.Text.Substring(textBox.SelectionStart + 45);
}}
To accomplish your goal the code could be changed in this way
//Loops through each line of text in RichTextBox
for (int i = 0; i < textBox.Lines.Length; i++)
{
string text = textBox.Lines[i];
//Checks if the line starts with "8".
if (text.StartsWith("8"))
{
// Find the 45th position from the start of the line
int startindex = textBox.GetFirstCharIndexFromLine(i) + 45;
// Starting from the found index select 1 char
textBox.Select(startindex, 1);
// Replace the selected char with the "P"
textBox.SelectedText = "P";
}
}
The key points changed are the way to select into a textbox. The Select method requires a starting index and the number of character to select, finally, once you have a SelectedText, (a read/write property) you can simply replace the current SelectedText with your own text. Lot easier than your current (and wrong) calculation.

how to increase array element by multiplying

Textbox2 has some 60 ids and i want to increase it to 250....
So i use following code increase the elements.
when i click the size button textbox2 should have 300 ids(now it has 60 only)..
lately i need to reduce it to 250 ids
. But it is getting exceptions
private void Size_Click(object sender, System.EventArgs e)
{
string[] vlist = textBox1.Text.Split('\n');
int size = (Convert.ToInt32(textBox2.Text)) / Convert.ToInt32(vlist) +1;
int p = Convert.ToInt32(textBox2.Text) * size;
textBox2.Text = p.ToString();
}
Please tell me what should i do in this?
private void Size_Click(object sender, System.EventArgs e)
{
List<string> vlist = new List<string>(textBox2.Text.Split('\n'));
int currentLineNumber = vlist.Count;
int targetLineNumber = Int32.Parse(textBox1.Text);
if (targetLineNumber == currentLineNumber)
return; //nothing to change
else if (targetLineNumber > currentLineNumber) //increase number of line
{
for (int i = currentLineNumber; i < targetLineNumber; ++i)
vlist.Add(vlist[(i - currentLineNumber) % currentLineNumber]);
}
else //reduce number of line
vlist = vlist.GetRange(0, targetLineNumber);
if (vlist.Count == 0)
textBox2.Text = String.Empty;
else
{
string result = vlist[0];
for (int i = 1; i < targetLineNumber; ++i)
result += String.Format("\n{0}", vlist[i]);
textBox2.Text = result;
}
}
The logic is quite simple. First, get number of line in textbox1 and target line number in textbox2. (This assume textbox1 is not empty though)
For increasing in size, we just keep adding id to the list until it reaches target size. For reducing size, it is even simpler, just take the first N lines from the list. After resizing, just reconnect all the lines together and set textBox1.Text to it.
You cannot change the array size.
If you want to have dynamic size you should use collections like List<T>
...
string[] vlist = textBox1.Text.Split('\n');
int size = (Convert.ToInt32(textBox2.Text)) / Convert.ToInt32(vlist.Length) +1;
string newString = "";
for(int i=0;i<size;i++){
newString = String.Join("\n",vlist);
textBox2.Text += newString + "\n";
}
...
This way, you append to the textbox the information you already got there (vlist), the number of times you need (size). I haven't tested it but probably this would repeat those IDs once more tan desired, in that case, remove the "+1" from the size variable definition
For the reduction to 250, you should specify which criteria are you following... if they are only the first 250, you could do that easily in a for loop with 250 as the break condition / top value

Enable Password Char in TextBox except last N character / Limit Masked Char

How to enable Password Char in TextBox except last N character?
I already tried this method
cardnumber.Select((c, i) => i < cardnumber.Length - 4 ? 'X' : c).ToArray()
But it is so hard to manipulate, I will pass original card value in every event like Keypress,
TextChange and etc..
Is there I way that is more simple and easy to managed?
This should do the trick,
string pw = "password1234";
char[] splitpw;
string cenpw;
int NtoShow;
splitpw = new char[pw.Length];
splitpw = pw.ToCharArray();
NtoShow = 4;
for (int i = 0; i < pw.Length; i++)
{
if (i < pw.Length - NtoShow)
cenpw += "*";
else
cenpw += splitpw[i];
}
//cenpw: "********1234"

How to make a loop repeat forever?

I am basically just wondering how can I make this while loop repeat continuously forever? I just can't figure out how to do it. once it reaches the end of the string it throws an exception. I have tried goto but it didn't work idk if i was just using it in the wrong play or what but i could get it work.
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (this.checkBox2.Checked)
{
int startIndex = 0;
string str = "hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii";
int length = str.Length;
while (true)
{
Application.DoEvents();
Thread.Sleep(200);
startIndex++;
string str2 = str.Substring(startIndex, 15);
label2.Text = str2;
if (startIndex == length)
{
startIndex = 0;
}
The last valid index in a string (or any array or list or collection) is always the length - 1, not length. Furthermore, since you are taking a substring of length 15, you actually want to stop 15 characters before the end. You'll want to change your if statement to be
if(startIndex == length - 16)
startIndex = 0;
Your while loop isn't the problem, it's your call to Substring.
Once startIndex becomes high enough, there aren't 15 more characters in the string...so Substring will thrown an ArgumentOutOfRangeException.
To fix the problem, you need to change your if statement to something like:
if(startIndex == length - 16)
if (startIndex + 15 == length)
{
startIndex = 0;
}

problem with converting numbers in textBox

The code below belongs to a binary search algorithm. The user enters numbers in textbox1 and enters the number that he want to find with binarysearch in textbox2. When I enter for example 16 in textBox2 and put breakpoint on the line I commented, I see that the value of searchnum is 10.
I think it converts to hexadecimal. I don't know why. Can you help me?
private void button1_Click(object sender, EventArgs e)
{
string[] source = textBox1.Text.Split(',');
int[] nums = new int[source.Length];
for (int i = 0; i < source.Length; i++)
{
nums[i] = Convert.ToInt32(source[i]);
}
string str_searchnum = textBox2.Text;
int searchnum = Convert.ToInt32(str_searchnum); // str_searchnum shows the value 16 but searchnum shows 10
int first = 0;
int last = nums.Length - 1;
while (1 < nums.Length - 1)
{
int mid = (int)Math.Floor(first + last / 2.0);
////if (first < last)
////{
//// break;
////}
if (searchnum < nums[mid])
{
last = mid - 1;
}
if (searchnum > nums[mid])
{
first = mid + 1;
}
else
{
MessageBox.Show(nums[mid].ToString());
}
}
}
Check to see if the debugger is set to display values using hexadecimal notation? You can find this option by right clicking in the watch window.
If that's not it, step through the entire method. What is the value of str_searchnum?
Although I personally prefer int.TryParse(), Convert.ToInt32() should be well-tested and not be doing any base conversions.
Why not use Array.BinarySearch? Also, your loop condition is (probably) wrong.

Categories