2017-09-21 5 views
0

私は何をしようとしていますこれは私がlistBoxフォルダ内のすべての.txtファイルを表示していますが、listBoxの.txtをクリックできるようにしたいrichTextBoxその.txtファイルのテキストを表示します。ファイル表示する コード:textBoxに表示するコードについてはリストボックスを読み込むにはrichtextBoxを取得する方法

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); 
    } 

は、私は多くのインターネットの回答を試してみましたが、持っているどこにも主なエラーであること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.FileInfo'と入力すると 'System.String'タイプのオブジェクトをキャストできません。

このことが起こったとのコメントがありましたが、男は変更行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; 
      } 
     } 
    } 
+1

* textBox *で表示するコードについては、コードとエラーがありますが、それもあなたの質問に追加できますか? –

+0

何を試しましたか?その部分を分かち合うことができますか?どの例外がこの例外を投げていますか? – Abhay

+0

私は他のものも試したことがあります。ほとんどの場合、それはうまくいったが、間違った結果(ファイル名やそれに類するもの)が表示される。 –

答えて

0

私はそれが私にいくつかの時間がかかったが、私は文書ではない名前を望んでいたので、私は、私はテキストを取得し、私はそれが役立つだろうとは思いませんでしたテキストボックスに移動することができることを実現したが、その後、私はそれをやりましたファイルパスとして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; 
      } 
     } 
    } 
0

なぜなら、リストボックスには文字列が格納されているからです。

あなたはそれらを変換しようとします。

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

いくつかのエラーを報告しますか?これらはどこに置く必要がありますか?私の謝罪はまったく新しいものです。 –

関連する問題