Changing only a specific line of a textbox

  • Thread starter Thread starter supster
  • Start date Start date
S

supster

I'de like to change only a specific line of a textbox.

Right now I am doing:



string[] texta = mainTextBox.Text.Split(
"\n".ToCharArray() );
for ( int i = 0; i <= texta.Length-1; i++ )
{
if(i == myLine)
mainTextBox.Text += "My New Text For This Line\r\n";
else
if(!(texta.Equals("")))
mainTextBox.Text += texta.ToString() +
"\n";
}


However doing this means the whole text box is rewritten, and this is
not a small box and will contain 100+ lines. Everytime it is
rewritten I can see the scrollbar go from small to large again as the
box is being written and theres a small 0.5-1sec pause while it
loops.

I tried using the textbox.line = "My Line", but it seems that the
line array of text boxes is only meant to be read from, not to set.

Anyone have any ideas??
 
supster said:
I'de like to change only a specific line of a textbox.

Right now I am doing:

string[] texta = mainTextBox.Text.Split(
"\n".ToCharArray() );
for ( int i = 0; i <= texta.Length-1; i++ )
{
if(i == myLine)
mainTextBox.Text += "My New Text For This Line\r\n";
else
if(!(texta.Equals("")))
mainTextBox.Text += texta.ToString() +
"\n";
}


Well that's a nasty start - you're telling it to redraw loads of times.
The first thing to do is:

string[] lines = mainTextBox.Text.Split('\n');

StringBuilder builder = new StringBuilder();
for (int i=0; i < lines.Length; i++)
{
if (i==myLine)
{
builder.Append ("My New Text For This Line\r\n");
}
else
{
builder.Append (lines);
builder.Append ('\n');
}
}
mainTextBox.Text = builder.ToString();

Give that a try and see if it's fast enough.
 
Wow, that is amazingly fast, but uses the same algorithm that I did.
The only difference is that I was writing to a string array and
you're writing to a StringBuilder.

Why is it so much faster? How does the StringBuilder work and store
the strings?
 
Anytime you change the value of a string, you actually create a new
string object in the managed heap.

example:

string s = "one";
s += " two";

It would appear that there is one string containing "one two", but the
heap actually contains two strings now, "one" and "one two". The
variable s now references "one two" and the string "one" waits for the
garbage collector. Put this in a loop of 100 and you now have 100
string objects, each one containing the old value plus the new
value. You can see how quickly this can use up memory waiting for the
GC to free up resources.

"one"
"one two"
"one two three" and so on.

This will help you understand the StringBuilder class:

http://msdn.microsoft.com/library/d...ml/frlrfsystemtextstringbuilderclasstopic.asp


Wow, that is amazingly fast, but uses the same algorithm that I did.
The only difference is that I was writing to a string array and
you're writing to a StringBuilder.

Why is it so much faster? How does the StringBuilder work and store
the strings?
 
Back
Top