c# How to read and write from multiline textBox line by line?

87,926

Solution 1

The property Lines is there for you

if(textBox1.Lines.Length > 0)
    textBox2.Text=textBox1.Lines[0]; 

or, put your textboxes ordered in a temporary array and loop on them (of course we should always check the number of lines present in textBox1)

TextBox[] text = new TextBox[] {textBox2, textBox3, textBox4};
if(textBox.Lines.Length >= 3)
{
    for(int x = 0; x < 3; x++) 
       text[x] = textBox1.Lines[x];
}

Solution 2

Simple programming read and write a one-by-one line from multiline textBox in C#

Write line one-by-one:

textbox1.AppendText("11111111+");
textbox1.AppendText("\r\n222222222");
textbox1.AppendText("\r\n333333333");
textbox1.AppendText("\r\n444444444");
textbox1.AppendText("\r\n555555555");

Read line one-by-one:

for (int i = 0; i < textbox1.Lines.Length; i++)
{
    textbox2.Text += textbox1.Lines[i] + "\r\n";
}

Solution 3

You can use following snippet for reading comma separated and newline separated values from multiline textbox -

 if (!string.IsNullOrEmpty(Convert.ToString(txtBoxId.Text)))
        {
            string IdOrder = Convert.ToString(txtBoxId.Text.Trim());

            //replacing "enter" i.e. "\n" by ","
            string temp = IdOrder.Replace("\r\n", ",");            

            string[] ArrIdOrders = Regex.Split(temp, ",");

            for (int i = 0; i < ArrIdOrders.Length; i++)
            {
              //your code
            }
         }

I Hope this would help you.

Share:
87,926
Manar Al Saleh
Author by

Manar Al Saleh

i am a small programer and i have no experince

Updated on July 05, 2022

Comments

  • Manar Al Saleh
    Manar Al Saleh almost 2 years

    I have a simple program it has a function to read a line from multiline textBox when i press a button what i made to do that is this code :

    TextReader read = new System.IO.StringReader(textBox1.Text);
    int rows = 100;
    
    string[] text1 = new string[rows];
    for (int r = 1; r < rows; r++)
    {
        text1[r] = read.ReadLine();
    }
    

    so when click button1 it the code will be like this:

    textBox2=text1[1];
    

    [1] mean the first line How can i do it automaticaly by one click ? or with one click the first line to textBox2 the second to textBox3 .....ect..

    plz i want the code and where i should put it ^_^

    or if there is another way to do that

  • Polyfun
    Polyfun over 11 years
    ...and TextBox.Lines is a string[], so it is an exact replacement for the text1 variable in the original post.
  • Manar Al Saleh
    Manar Al Saleh over 11 years
    a want to do a loop for [1] [2] [3] string how can i do it
  • Douglas Timms
    Douglas Timms over 7 years
    Note: Textbox.lines is only available for Windows Forms (not webforms)