c# - 尝试从 txt 文件填充文本框和列表视图

c# - Trying to populate textbox and listview from txt file

我只能加载文本框,似乎无法填充列表视图。但是,在我删除 this.textBox1.Text = sr.ReadToEnd(); 后,列表视图已填充。这是代码:

using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
    string line = String.Empty;
    this.textBox1.Text = sr.ReadToEnd(); // remove it, listview working
    while ((line = sr.ReadLine()) != null)
    {
        string[] data = line.Split(new char[0]);
        ListViewItem item = new ListViewItem
        {
            Text = data[0]
        };
        item.SubItems.Add(data[1]);
        listView1.Items.Add(item);
    }
}

截图: Img1 Img2

好吧,sr.ReadToEnd() 读取文件直到最后,这就是 ReadLine() 没用的原因。

让我们逐行读取文件 并更新 text(我们将分配给 this.textBox1.Text)和 listView1.Items

StringBuilder text = new StringBuilder();

bool firstLine = true; 

// We don't want redrawing after each ListViewItem adding
listView1.BeginUpdate();

try {
  // File.ReadLines is easier to manipulate with StreamReader
  // if you want just read lines
  foreach (string line in File.ReadLines(openFileDialog1.FileName)) {
    if (!firstLine)
      sb.AppendLine();

    sb.Append(line);
    firstLine = false; 

    // 3: We want at most 3 chunks (item, subitem and tail to throw away)
    string[] data = line.Split(new char[0], 3);

    ListViewItem item = new ListViewItem() {
      Text = data[0]
    };

    if (data.Length > 1)
      item.SubItems.Add(data[1]);

    listView1.Items.Add(item);
  }
}
finally {
  // The file has been scanned, items added; now we a ready to redraw the listView1   
  listView1.EndUpdate();
}

this.textBox1.Text = text.ToString();

您可以使用以下内容。

ReadToEnd 这样做:读取从当前位置到流末尾的所有字符。你正在失去流的位置。

using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
    string line = String.Empty;
    StringBuilder sb = new StringBuilder();
    // this.textBox1.Text = sr.ReadToEnd(); // remove it, listview working
    while ((line = sr.ReadLine()) != null)
    {
        string[] data = line.Split(new char[0]);
        ListViewItem item = new ListViewItem
        {
            Text = data[0]
        };
        item.SubItems.Add(data[1]);
        listView1.Items.Add(item);
        sb.AppendLine(line);
    }
    this.textBox1.Text = sb.ToString();
}

你可以试试这个:

string filename = openFileDialog1.FileName;
var lines = File.ReadAllLines(filename);
textBox1.Text = string.Join(Environment.NewLine, lines);
foreach ( string line in lines )
{
  var items = line.Split(new char[0]);
  if ( items.Length > 0 )
  {
    var item = new ListViewItem(items[0]);
    if ( items.Length > 1 )
      item.SubItems.Add(items[1]);
    listView1.Items.Add(item);
  }
}