从文件加载列表框 [英] Loading a listbox from a file
本文介绍了从文件加载列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我第一次创建一个C#程序,所以我很抱歉,如果这个问题似乎基本。我有我的设计形式在3个列表框以及3个按钮,我想项目列表加载到每个文本框中当我点击相应的按钮,列表框。有人可以教我如何做到这一点。
This is my first time creating a C# program so I apologize if this question seems basic. I have 3 list boxes on my design form along with 3 buttons I'd like to load a list of item into each text box when I click the corresponding button for the listbox. can someone instruct me on how to do this.
推荐答案
阿巴斯已经给了你足够的答案,但有几个问题有了它,所以我想我会添加自己的反应。问题:
Abbas has given you a sufficient answer, but there are a couple of problems with it, so I thought I would add my own response. The issues:
- 流(任何实现
的IDisposable
)后需要被关闭你与他们完成。您可以通过手动调用的Dispose()
或包裹在使用
块中的对象的创建做到这一点。 - 您不应该由一个像,在情况下将项目添加到列表框中选择一个有大量的物品。这将导致性能下降,并在列表框中会闪烁,因为它更新添加每个项目后/重绘。
- Streams (anything that implements
IDisposable
) need to be closed after you're done with them. You can do this by manually callingDispose()
or by wrapping the creation of the object in ausing
block. - You shouldn't add items to the list box one by one like that in case there are a large number of items. This will cause poor performance and the list box will flicker as it updates/redraws after each item is added.
我会做这样的事情这样的:
I would do something like this:
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 );
}
}
这篇关于从文件加载列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文