简体   繁体   中英

How to change what a combo box displays

I have a combo box in ac# windows form app project, i used the following code to make a combo box display to content of the file folder

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

It does work but the combo box contains the full paths of the files in the folder, what i want to ask you is is there a way to make it so the combo box will only display the files name but the actual values of the combo box will remain the full path?

You can set the DataSource of the combobox to the FileInfo list returned by a DirectoryInfo class, then set the ValueMember to the FullName property and the DisplayMember to the Name property

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";

Now to get back the fullname of your file you use the property SelectedValue

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

Finally, whatever you want to do with that file, remember that each item in the ComboBox is a FileInfo instance, so you can read the SelectedItem property to discover information about your selected file, like Attributes, CreationDate, Length etc...

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

There is not really an out-of-the-box solution for this, so you'll needa write a handful of lines of background code. Use, for instance, an IDictionary with the files names as keys and the full paths as values. Then insert an event handler triggered every time the user picks an entry in the combo box to activate the corresponding dictionary entry.

Sorry that I can't present you any ready-to-use code snippets as I had the same issue in a Gtk# app, not in Windows Forms. But I strongly hope you'll find my hint helpful.

What you can do is: Create a class that has the Properties FileName and FullPathAndFileName and overrides ToString method. The combobox will display the return of ToString and you will have the SelectedItem which you can access by the properties.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM