如何让 richTextBox 读取列表框

How to get a richTextBox to read listbox

我想做的是我有一个 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;
            }
        }
    }

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

你必须尝试转换它们。

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

我做到了,这花了我一些时间,但我意识到我可以获取文本并将其移动到文本框中我认为这不会有帮助,因为我想要文档而不是名称但后来我把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;
            }
        }
    }