Reputation: 16724
I'm using the following code in _TextChanged
:
string[] currentLines = new string[text.Lines.Length];
for (int i = 0; i < currentLines.Length; i++) {
currentLines[i] = text.Lines[i] + "...";
}
text.Lines = currentLines;
that's crashing when event is called. I have no idea how to fix this, the crash occurring when I do this:
text.Lines = currentLines;
why's that and how to fix? Thanks in advance.
Upvotes: 1
Views: 284
Reputation: 16724
The solution:
For a reason that I don't know(if you know, explain for me, please), this crash occurs only with TextBox
, I replaced to a RichTextBox
and it works fine now.
Upvotes: 0
Reputation: 27713
Perhaps try unsubscribing from the _TextChanged
event before the problematic line, and re-subscribing after it.
Upvotes: 0
Reputation: 3125
Setting Lines may trigger the _TextChanged
event again. What is the error you are getting? If you see a StackOverflowException, this is the cause.
You could possibly add this to get around the problem, or take the bool flag approach Daniel mentioned in his answer.
text.TextChanged -= textBox1_TextChanged;
text.Lines = currentLines;
text.TextChanged += textBox1_TextChanged;
Also, perhaps this question discussing the difference between programmatic changes and user driven changes is of interest to you.
Upvotes: 4
Reputation: 174417
As Adam S notes in his answer, you are most likely getting a StackOverflowException
because of endless recursion. You can try to fix it like this:
private void _TextChanged(...)
{
static bool settingLines = false;
if(settingLines)
return;
string[] currentLines = new string[text.Lines.Length];
for (int i = 0; i < currentLines.Length; i++) {
currentLines[i] = text.Lines[i] + "...";
}
settingLines = true;
text.Lines = currentLines;
settingLines = false;
}
This solution is not thread safe but that is not a problem in your case as you are interacting with UI controls anyway.
Upvotes: 1