2009-08-14 58 views
0

我有一個Windows應用程序,它將文本框中的數據寫入到隨機生成的文本文件中,並保存日誌。然後是列出所有這些單獨的日誌文件的列表框。我想要做的事情是讓另一個列表框顯示選中的文件信息,第二,第7,第12,...,第(2 + 5n)行按鈕列表後選擇的文本文件信息「被點擊。怎麼可能做到這一點?如何獲取在列表框中選擇的文件信息?

我的代碼更新列表框第一是:

private void button2_Click(object sender, EventArgs e) 
    { 
     listBox1.Items.Clear(); 

     DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\Ece\Documents\Testings"); 
     // What type of file do we want?... 

     FileInfo[] Files = dinfo.GetFiles("*.txt"); 
     // Iterate through each file, displaying only the name inside the listbox... 

     foreach (FileInfo file in Files) 
     { 
      listBox1.Items.Add(file.Name + "   " +file.CreationTime); 
     } 

    } 
+3

........什麼! ?! – Gineer 2009-08-14 11:46:35

回答

3

在你想獲得所選項目的SelectedIndexChanged事件。我不會建議在另一個列表框中顯示第二部分,但我相信你可以從下面的例子中看出如果你需要它。我個人有一個RichTextBox,只是讀文件有:

//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(); 

或者如果你是持續性與ListBox的堅持,那麼:

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

string CurrentLine = ""; 
int LineCount = 0; 

//While it is not the end of the file 
while(FileRead.Peek() != -1) 
    { 
    //Read a line 
    CurrentLine = FileRead.ReadLine(); 

    //Keep track of the line count 
    LineCount++; 

    //if the line count fits your condition of 5n + 2 
    if(LineCount % 5 == 2) 
    { 
    //add it to the second list box 
    listBox2.Items.Add(CurrentLine); 
    } 
    } 

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

不完全是海報找的東西,儘管我無法弄清楚海報在找什麼...... – 2009-08-14 11:49:07

+0

總是說'System.String'類型的對象不能轉換成'System.IO.FileInfo'類型。 – 2009-08-14 12:11:12

+0

FileInfo SelectedFileInfo =(FileInfo)listBox1.SelectedItem;這一個給出了錯誤 – 2009-08-14 12:14:23

相關問題