-1

I have a window form application, and there are several textboxs in this winform. I want to select the textfile from combobox and fill the text inside each of the textbox.

What I currently done:

(I write to textfile before select from combobox)

string fn = ....
string combine = string.Join(",", richTextBox1.Text, richTextBox2.Text, richTextBox3.Text)
File.WriteAllText(fn, combine);

Below is the select file and fill in the textbox function:

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
    {
        using (StreamReader streamReader = new StreamReader(comboBox2.Text))
        {
            string line = string.Empty;
            while ((line = streamReader.ReadLine()) != null)
            {
               
                string[] tempArray = line.Split(',');
                richTextBox1.Text = tempArray[0]; richTextBox2.Text = tempArray[1]; richTextBox3.Text = tempArray[2];

            }
        }
    }        

This can fill in the textbox successfully when select from combobox if the text that fill in the textbox before is only in one line.{hello, how are you?i am fine,hi) However, when i type sentence with newline and write to textfile...For example,

*hello,how are you?

i am fine, hi*

When I load the file, it will come out with an error which is "Index was outside bound of array". How should I solve this error if i want to load the file that have sentence with newline?

yancy
  • 17
  • 6

1 Answers1

0

You get this error because you are referring to an index that doesn't exist, for example tempArray[2], because when the line is split it only has two items on the first line tempArray[0] = "*hello" and tempArray[1] = "how are you?", and the same for the second line.

It is very bad practice to split everything up into individual hard coded text boxes, instead, it should all go into a single text box on new lines so that you don't have issues if you have more than 3 bits of data.

For example this would read everything into a single text box on new lines:

while ((line = streamReader.ReadLine()) != null)
{
    string[] tempArray = line.Split(',');
    
    for (int i = 0; i < tempArray.Length; i++) 
    {
        //Use the dynamic i index
        //Add \r\n to the end to move down a line
        richTextBox1.AppendText(tempArray[i] + "\r\n"); 
    }
}
sorifiend
  • 5,927
  • 1
  • 28
  • 45