gpt4 book ai didi

c# - 从文件加载列表框

转载 作者:太空宇宙 更新时间:2023-11-03 19:28:00 24 4
gpt4 key购买 nike

这是我第一次创建 C# 程序,如果这个问题看起来很基础,我深表歉意。我的设计表单上有 3 个列表框以及 3 个按钮 我想在单击列表框的相应按钮时将项目列表加载到每个文本框中。有人可以指导我如何执行此操作。

最佳答案

Abbas 已经给了你一个充分的答案,但它有几个问题,所以我想我会添加我自己的回应。问题:

  1. Streams(任何实现IDisposable 的东西)在你用完之后需要关闭。您可以通过手动调用 Dispose() 或将对象的创建包装在 using block 中来执行此操作。
  2. 您不应该像这样将项目一个一个地添加到列表框中,以防项目数量很多。这会导致性能不佳,列表框会在添加每个项目后更新/重绘时闪烁。

我会做这样的事情:

using System.IO;
// other includes

public partial class MyForm : Form
{
public MyForm()
{
// you can add the button event
// handler in the designer as well
someButton.Click += someButton_Click;
}

private void someButton_Click( object sender, EventArgs e )
{
PopulateList( "some file path here" );
}

private void PopulateList( string filePath )
{
var items = new List<string>();
using( var stream = File.OpenRead( filePath ) ) // open file
using( var reader = new TextReader( stream ) ) // read the stream with TextReader
{
string line;

// read until no more lines are present
while( (line = reader.ReadLine()) != null )
{
items.Add( line );
}
}

// add the ListBox items in a bulk update instead of one at a time.
listBox.AddRange( items );
}
}

关于c# - 从文件加载列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7133338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com