Question

I am a beginner. I have code to read in a text file, and part of how to get the strings into a text box. The format of the text file is like DREC: 04HF; and then the next begins with that same format. I need to read that from the text file and split it into 2 separate text boxes (3,4) at a : or a ; . Thank you for the help.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog of = new OpenFileDialog();
        of.ShowDialog();
        textBox1.Text = of.FileName;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        StreamReader sr = new StreamReader(textBox1.Text);
        textBox2.Text = sr.ReadToEnd();
        sr.Close();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        int lcount;
        string s;
        int i;
        lcount = textBox2.Lines.Length;
        s = textBox2.Lines[0];
        for (i = 0; i < lcount; i++)
        {

            textBox4.Text = textBox2.Lines[i];
        }
        textBox4.Text = s;
    }
}
Was it helpful?

Solution

I need a better description of what you are doing but maybe this will help

//split apart segments
string[] split1 = textBox2.Text.Split(';');
foreach (string segment in split1)
        {
            //split sub-segment
            string[] split2 = segment.Split(':');

            //check if it's valid
            if (split2.Count().Equals(2))
            {
                textBox3.Text += String.Format("{0}{1}", split2[0].Trim(), Environment.NewLine);
                    textBox4.Text += String.Format("{0}{1}", split2[1].Trim(), Environment.NewLine);
            }
            else
            {
                throw new ArgumentException("Invalid Segment");
            }
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top