0

Is there any way to show string array items in textbox seperated with comma. I am unable to get it right, running through lots of trials and errors.

Any help or suggestion with be highly appreciated.

private void button9_Click(object sender, EventArgs e)
    {
        int lineNum = 1;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.Filter = "Text Files|*.txt";
        openFileDialog1.Title = "Select a Text file";
        openFileDialog1.FileName = "";
        DialogResult result = openFileDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            string file = openFileDialog1.FileName;

            string[] text = System.IO.File.ReadAllLines(file);



            foreach (string line in text)
            {
                if (lineNum <= 30)
                {

                    textBox1.Text = Convert.ToString( text);

                }
                else
                {
                   textBox2.Text = Convert.ToString(text);
                 }
            }
        }
   }

Any suggestion please

2 Answers 2

5

Sure, just use String.Join

textBox1.Text = string.Join(",", text);

If you want to append NewLine after each comma use:

textBox1.Text = string.Join("," + Environment.NewLine, text);

Also you don't need to use that foreach loop.

Edit: According to your comment you can use something like this:

textBox1.Text = string.Join("," + Environment.NewLine, text.Take(30));

if(text.Length > 30)
     textBox2.Text = string.Join("," + Environment.NewLine, text.Skip(30));

Note: In order to use LINQ methods (for ex. Take and Skip) you need to include System.Linq namespace to your project.

using System.Linq;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot @Selman22 it works and displays all items in array in textbox seperated with comma, but as u can see in my codes, i want to display 1st 30 items of the array textbox1 others in textbox2. but the code is skipping condition check.
@user2889827 I edited my answer.it should do what you want :)
1

@user2889827 With you code you are making this error: every new loop cycle you replace the hold Textbox1.Text with a new string.
For correcting this problem you must concatenate the hold text with the new one:

...
textbox1.text+=text;
...
textbox2.text+=text;

Also converting a string to a string it's useless.
Or if you prefer you can use the @Selman22 solution that, in you case, is the best solution for solving the problem

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.