tags:

views:

48

answers:

2

Hi,

I would like to insert text in a particular line, and replacing the text in the same line.

Eg

This is line 1
This is line 2
This is line 3

Now i would like to replace the text in line 2 to this is new line 2

is this possible?

+3  A: 

One option is to split the text on line breaks, change the second element of the resultant array, and then rejoin into a string and set the Text property. Something like

string[] array = textBox.Text.Split('\n');
array[position] = newText;
textBox.Text = string.Join('\n', array);
Anthony Pegram
A: 

You could use the RegEx object to split the text.

Call the ReplaceLine() method like this:

    private void btnReplaceLine_Click(object sender, RoutedEventArgs e)
    {
        string allLines = "This is line 1" + Environment.NewLine + "This is line 2" + Environment.NewLine + "This is line 3";
        string newLines = ReplaceLine(allLines, 2, "This is new line 2");
    }

The ReplaceLine() method implementation:

        private string ReplaceLine(string allLines, int lineNumber, string newLine)
    {
        System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(Environment.NewLine);

        string newLines = "";

        string[] lines = reg.Split(allLines);

        int lineCnt = 0;
        foreach (string oldLine in lines)
        {
            lineCnt++;

            if (lineCnt == lineNumber)
            {
                newLines += newLine;
            }
            else
            {
                newLines += oldLine;
            }

            newLines += lineCnt == lines.Count() ? "" : Environment.NewLine;
        }

        return newLines;
    }
ChrisNel52