2017-01-02 56 views
1

我有一個組合框在C#Windows窗體應用程序項目,我用什麼下面的代碼,以使組合框顯示到如何更改組合框顯示

string path = Path.GetFullPath("a").Replace(@"\bin\Debug\a", "") + @"\Files"; 
BotOptions.DataSource = Directory.GetFiles(path); 

它確實該文件夾的內容工作,但組合框包含文件夾中的文件的完整路徑,我想問你的是有沒有辦法使它,所以組合框將只顯示文件的名稱,但組合框的實際值將保持完整的道路?

回答

5

可以設置組合框由DirectoryInfo類返回FileInfo的列表的數據源,然後設置ValueMember到FullName屬性和將DisplayMember對Name屬性

string path = Path.GetFullPath("a").Replace(@"\bin\Debug\a", "") + @"\Files"; 
DirectoryInfo de = new DirectoryInfo(path); 
BotOptions.DataSource = de.EnumerateFiles().ToList(); 
BotOptions.ValueMember = "FullName"; 
BotOptions.DisplayMember = "Name"; 

我們找回全名文件的使用屬性SelectedValue

string fullPath = BotOptions.SelectedValue?.ToString(); 

最後,不管你想要做這個文件,記得在下拉列表中的每一項都是一個FileInfo實例,所以你可以閱讀塞萊ctedItem屬性來發現有關你選擇的文件,如屬性,CreationDate,長度等...

if(BotOptions.SelectedItem != null) 
{ 
    FileInfo fi = BotOptions.SelectedItem as FileInfo; 
    Console.WriteLine("File length: " + fi.Length); 
} 
0

是不是真的有這一個徹頭徹尾的現成的解決方案,所以你會needa寫的後臺代碼行的屈指可數。例如,使用IDictionary,其中文件名稱爲鍵,完整路徑爲值。然後插入一個事件處理程序,每當用戶在組合框中選擇一個條目以激活相應的字典條目時觸發。

對不起,我不能提出任何你準備使用的代碼片段,我在一個GTK#應用程序有同樣的問題,而不是在Windows窗體。但我強烈希望你會發現我的提示很有幫助。

0

你可以做的是: 創建具有屬性文件名和FullPathAndFileName並重寫ToString方法的類。組合框將顯示ToString的返回值,並且您將擁有可以通過屬性訪問的SelectedItem。

public class ComboBoxItemForPathAndFileName 
{ 
    public ComboBoxItemForPathAndFileName(string fileName, string fullPathAndFileName) 
    { 
     this.FileName = fileName; 
     this.FullPathAndFileName = fullPathAndFileName; 
    } 

    public string FileName{get;set;} = string.Empty; 
    public string FullPathAndFileName{get;set;} = string.Empty; 

    public override ToString() 
    { 
     return this.FileName; 
    } 
}