2014-04-01 10 views
0

我有有像C#分割文本文件,并显示它分成两个不同的列表框

daniel : dawson 
jack : miller 
frozen : mass 
ralph : dcosta 

我想在TextBox2中冒号其中ListBox1中含有丹尼尔和listbox2后显示在ListBox1中和文本冒号前的文本字符的文本文件包含道森。代码到目前为止,

  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; 

       StreamReader reader = new StreamReader(file); 
       List<string> users = new List<string>(); 
       while (!reader.EndOfStream) 
       { 
        string line = reader.ReadLine(); 
        string[] tokens = line.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); 
        foreach (string s in tokens) 
        { 
         if (true) 
         { 

          listBox3.Items.Add(s) ; 

         } 
         listBox4.Items.Add(s); 


        } 
       } 
} 

和上面代码的输出是:

Lisbox1  Lisbox2 
daniel  daniel 
dawson  dawson 
jack  jack 
miller  miller 

,而我工作的

listbox1  listbox2 
daniel   dawson 
jack   miller 

任何帮助将不胜感激,谢谢

+0

ot'if(true)'是什么意思? –

回答

1

删除foreach,只需将tokens[0]添加到listBox3tokens[1]listBox4这样的:

if(tokens.Length >= 2) 
{ 
    listBox3.Items.Add(tokens[0]); 
    listBox4.Items.Add(tokens[1]); 
} 
+0

它像一个魅力工作:)谢谢 – sauk

1

替换此代码:

foreach (string s in tokens) 
{ 
    if (true) 
    { 
     listBox3.Items.Add(s); 
    } 
    listBox4.Items.Add(s); 
} 

由:

if(tokens.Length == 2) 
{ 
    listBox3.Items.Add(tokens[0]); 
    listBox4.Items.Add(tokens[1]); 
} 
else 
    MessageBox.Show("Invalid line input !!!!"); 

也是要确保所有名称中不包含空格地址:

string line = reader.ReadLine().Trim();