【问题标题】:How to get a richTextBox to read listbox如何让richTextBox读取列表框
【发布时间】:2017-09-21 04:58:08
【问题描述】:

我想要做的是我有一个listBox,它显示一个文件夹中的所有.txt 文件,但我希望能够单击listBox 中的一个.txt 并让我的richTextBox 显示该 .txt 文件中的文本。 显示文件的代码:

    private void Scripts_Load(object sender, EventArgs e)
    {
        DirectoryInfo dinfo = new DirectoryInfo(@"scripts");
        FileInfo[] Files = dinfo.GetFiles("*.txt");
        foreach (FileInfo file in Files)

            list.Items.Add(file.Name);
    }

至于textBox 中显示的代码,我尝试了很多互联网答案,但主要错误是Argument 1: cannot convert from 'object' to 'string' 我得到的最接近的是这个

    //Get the FileInfo from the ListBox Selected Item
FileInfo SelectedFileInfo = (FileInfo) listBox.SelectedItem;  

//Open a stream to read the file  
StreamReader FileRead = new StreamReader(SelectedFileInfo.FullName);

//Read the file to a string
string FileBuffer = FileRead.ReadToEnd();

//set the rich text boxes text to be the file
richTextBox.Text = FileBuffer;

//Close the stream so the file becomes free!
FileRead.Close();

它崩溃说:`System.InvalidCastException:'无法将'System.String'类型的对象转换为'System.IO.FileInfo'类型。'

已经有评论说发生了这种情况,那个人回答说将第 1 行更改为 FileInfo SelectedFileInfo = new FileInfo(listBox1.SelectedItem);这个失败的说法Argument 1: cannot convert from 'object' to 'string' `

我做到了耶!!!

        private async void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string value1 = list.SelectedItem.ToString();
        richTextBox1.Text = value1;
        using (StreamReader sr = new StreamReader("scripts\\" + value1))
        {
            {
                String line = await sr.ReadToEndAsync();
                richTextBox1.Text = line;
            }
        }
    }

【问题讨论】:

  • 至于在文本框中显示的代码你提到了代码和错误,你能把它也添加到你的问题中吗?
  • 你试过什么?你能分享那部分吗?哪一行抛出了这个异常?
  • 我还尝试了其他一些我从未想过会起作用的东西。在大多数情况下,它确实有效,但结果错误(它会列出文件名或类似名称)。

标签: c# listbox richtextbox streamreader


【解决方案1】:

原因是您的列表框中存储了字符串。

您必须尝试转换它们。

        var filename as listBox.SelectedItem as string;
        if(string.IsNullOrWhiteSpace(filename))
        {
            return;
        }
        var path = Path.Combine(@"C:\", filename);
        var fileinfo = new FileInfo(path);

【讨论】:

  • 出现一些错误,我必须把这些放在哪里?抱歉,我是新手。
【解决方案2】:

我做到了,我花了一些时间,但我意识到我可以获取文本并将其移动到文本框我认为这没有帮助,因为我想要文档而不是名称,但我将 Var 设置为文件路径,这里:

        private async void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string value1 = list.SelectedItem.ToString();
        richTextBox1.Text = value1;
        using (StreamReader sr = new StreamReader("scripts\\" + value1))
        {
            {
                String line = await sr.ReadToEndAsync();
                richTextBox1.Text = line;
            }
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多