Neel Maheta
Neel Maheta

Reputation: 339

Change Particular line of Multiline textbox in C#

I am unable to Change the specific string of a multiline TextBox.

suppose first line of multiline textbox is "Hello" & second line is "Bye".But when i trying to change the value of second line like below.

textBox1.Lines[1] = "Good bye";

When I saw the result using Debug mode it was not "Good bye".

I also read this MSDN article & this stackoverflow question but can't get the desired answer.

Upvotes: 3

Views: 5791

Answers (4)

arbiter
arbiter

Reputation: 9605

Working with TextBox lines via Lines property are extremely ineffective. Working with lines via Text property is a little better, but ineffective too.

Here the snippet, that allows you to replace one line inside TextBox without rewriting entire content:

public static bool ReplaceLine(TextBox box, int lineNumber, string text)
{
    int first = box.GetFirstCharIndexFromLine(lineNumber);
    if (first < 0)
        return false;

    int last = box.GetFirstCharIndexFromLine(lineNumber + 1);

    box.Select(first,
        last < 0 ? int.MaxValue : last - first - Environment.NewLine.Length);
    box.SelectedText = text;

    return true;
}

Upvotes: 1

Azar Shaikh
Azar Shaikh

Reputation: 449

First you need assign textBox1.Lines array in variable

string[] lines = textBox1.Lines; 

Change Array Value

lines[1] = "Good bye"; 

Reassign array to text box

textBox1.Lines=lines; 

According to MSDN

By default, the collection of lines is a read-only copy of the lines in the TextBox. To get a writable collection of lines need to assign new string array

Upvotes: 1

ˈvɔlə
ˈvɔlə

Reputation: 10272

You could try to replace the text of second line like this:

    var lines = textBox.Text.Split(new[] { '\r', '\n' }).Where(x => x.Length > 0);
    textBox.Text = textBox.Text.Replace(lines.ElementAt(1), "Good bye");

Upvotes: 0

Nino
Nino

Reputation: 7115

As MSDN states (the link you provided):

By default, the collection of lines is a read-only copy of the lines in the TextBox. To get a writable collection of lines, use code similar to the following: textBox1.Lines = new string[] { "abcd" };

So, you have to "take" Lines collection, change it, and then return to TextBox. That can be achieved like this:

var lines = TextBox1.Lines;
lines[1] = "GoodBye";
TextBox1.Lines = lines;

Alternatively, you can replace text, like Wolle suggested

Upvotes: 5

Related Questions