c#将字符串拆分为单独的文本框

时间:2014-05-08 16:43:35

标签: c# string loops textbox split

我是初学者。我有代码在文本文件中读取,以及如何将字符串放入文本框的部分内容。文本文件的格式类似于DREC:04HF;然后下一个以相同的格式开始。我需要从文本文件中读取它并将其分成两个单独的文本框(3,4):a或a; 。谢谢你的帮助。

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;
    }
}

1 个答案:

答案 0 :(得分:0)

我需要更好地描述你在做什么,但也许这会有所帮助

//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");
            }
        }
相关问题