根据选择的项目将文本文件加载到文本框中 [英] Load the text file into the textbox depending on which item is selected

查看:77
本文介绍了根据选择的项目将文本文件加载到文本框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 

我正在研究我的一个程序,而且我遇到了一个我无法弄清楚的问题。基本上,您可以将程序中的脚本下载到其目录中,然后列表框将自动列出脚本包中的项目。现在是下一个
部分,将文本文件加载到文本框中。我可以继续为这些脚本中的每一个创建一个if语句,但这将是非常耗时且非常糟糕的方法。所以我的问题是:我怎样才能这样做,根据列表框中选择的
项目,它会将相应的文本文件加载到文本框中,而不会为每个文本框中的每一个都添加大量的if语句?谢谢:)

I'm working on one of my programs and I've come across a problem I cannot figure out. So basically, you can download scripts in my program to it's directory and then the listbox will automatically list the items from the scripts pack. Now comes the next part, loading the text files into the textbox. I can just go ahead and make an if statement for every one of these scripts but that would be very time consuming and a really bad way of doing it. So my question is: How can I make it so that, depending on the item selected in the listbox, it would load the appropriate text file into the textbox without making a ton of if statements for each and every one of them? Thanks :)

推荐答案

也许不是用字符串加载ListBox而是将数据源设置为列表。在这种情况下,列表是

Perhaps instead of loading the ListBox with strings set the data source to a list. In this case the list is

public class ScriptItem
{
    public string DisplayText { get; set; }
    public string FileName { get; set; }
    public override string ToString()
    {
        return DisplayText;
    }
}

创建列表

var scriptItems = new List<ScriptItem>();

对于要放入ListBox的每个项目

For each item to place in the ListBox

scriptItems.Add(new ScriptItem()
{
    DisplayText = "TODO",
    FileName = "Full name of file and path if needed"
});




设置ListBox的DataSource

Set the DataSource of the ListBox

listBox1.DataSource = scriptItems;

在ListBox中更改选择时获取它

Get it on selection changed in the ListBox

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listBox1.SelectedItem != null)
    {
        var scriptItem = (ScriptItem) listBox1.SelectedItem;
        var fileName = scriptItem.FileName;
    }
}


这篇关于根据选择的项目将文本文件加载到文本框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆