2016-10-26 35 views
-1

加載一個文件,我現在有下面的代碼:如何從組合框

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 
    Dim dir = "Path\path\path" 
    For Each file As String In System.IO.Directory.GetFiles(dir) 
     ComboBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file)) 
    Next 

End Sub 

這個代碼是找到一個目錄,並填充在該目錄中的所有文件的名稱的組合框。我希望能夠從組合框中選擇文件名並打開文件。

回答

1

在組合框雙擊,組合框項目更改時 - 推出在下拉列表中列出的文件:

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged 
    Dim proc As New System.Diagnostics.Process() 
    proc.StartInfo.FileName = ComboBox1.Text 
    proc.StartInfo.WorkingDirectory = "Path\path\path" 
    proc.Start() 
End Sub 
+0

這就像一個魅力!謝謝! – Enigma04

0

首先,你必須用GetFileName(文件)替換GetFileNameWithoutExtension(文件),因爲它可以進入副本

然後,只需添加以下代碼:

Process.Start(dir & combobox1.selectedText) 
+0

我在哪裏添加此代碼?我似乎無法得到它的工作。 – Enigma04

+0

只需雙擊組合框,就可以創建處理combobox.selectedindexchanged事件的函數。添加代碼到它 – Hadi

+0

或者添加一個按鈕,並在button.click事件 – Hadi

0

我會做這樣的

Private Sub LoadCombo(filesFromPath As String) Handles Button1.Click 

    cbo.DisplayMemeber = "Name" 
    cbo.ValueMemeber = "Value" 
    cbo.DataSource = System.IO.Directory.GetFiles(dir). 
     Select(Function(f) New With { .Name = f.Substring(f.LastIndexOf("\") + 1), .Value = f}) 


End Sub 

Private Sub cbo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbo.SelectedIndexChanged 

    If cbo.SelectedIndex = -1 Then Return 
    If Not File.Exist(cbo.SelectedItem.Value) Then Return '<-- this is late 
    ' binding that comes with anonymous type.) 

    Dim p As New Process() 
    p.StartInfo.FileName = cbo.SelectedItem.Value '<-- this is late binding that comes with anonymous type. 
    ' you can also declare your type and use : 
    ' p.StartInfo.FileName = DirectCastcbo(cbo.SelectedItem, yourType).Value 
    p.StartInfo.Arguments = ""; 
    p.StartInfo.ErrorDialog = true; 
    p.StartInfo.WindowStyle = ProcessWindowStyle.Normal; 
    p.Start(); 
End Sub