我有一个文本文件,其中包含
等字符daniel : dawson
jack : miller
frozen : mass
ralph : dcosta
我想在listbox1中显示冒号前的文本,在textbox2中显示冒号后的文本,其中listbox1包含daniel,listbox2包含dawson。代码到目前为止,
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 :(得分:1)
删除foreach
,然后将tokens[0]
添加到listBox3
,将tokens[1]
添加到listBox4
,如下所示:
if(tokens.Length >= 2)
{
listBox3.Items.Add(tokens[0]);
listBox4.Items.Add(tokens[1]);
}
答案 1 :(得分:1)
替换此代码:
foreach (string s in tokens)
{
if (true)
{
listBox3.Items.Add(s);
}
listBox4.Items.Add(s);
}
by:
if(tokens.Length == 2)
{
listBox3.Items.Add(tokens[0]);
listBox4.Items.Add(tokens[1]);
}
else
MessageBox.Show("Invalid line input !!!!");
还要确保所有名称都不包含空格add:
string line = reader.ReadLine().Trim();