Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CheckedListBox Display Different String c#

Tags:

c#

winforms

I have a CheckedListBox on a backup application I am writing. I want the user to pick the folders they want backing up i.e. desktop I have my for loop working for each ticked item etc but I want the user to see the tick box labeled as "Desktop" rather than c:\users\username\desktop

Can someone inform me how to change the listbox label to something different than what is actually being returned to my for loop.

like image 381
meeeeeeeeee Avatar asked Feb 20 '26 13:02

meeeeeeeeee


1 Answers

You should create a type that holds the full path and override ToString() to return what you want to display in the CheckedListBox. CheckedListBox.SelectedItems will then hold a list of your type.

    public void PopulateListBox()
    {
        _checkedListBox.Items.Add(new BackupDir(@"C:\foo\bar\desktop", "Desktop"));
    }

    public void IterateSelectedItems()
    {
        foreach(BackupDir backupDir in _checkedListBox.CheckedItems)
            Messagebox.Show(string.format("{0}({1}", backupDir.DisplayText, backupDir.Path));            
    }

    public class BackupDir
    {
        public string Path { get; private set; }
        public string DisplayText { get; private set; }

        public BackupDir(string path, string displayText)
        {
            Path = path;
            DisplayText = displayText;
        }

        public override string ToString()
        {
            return DisplayText;
        }
    }

you could of course strip the folder name from the path if that is what you wanted to do for every list item and just have the path arg on the BackupDir class.

like image 62
Myles McDonnell Avatar answered Feb 23 '26 03:02

Myles McDonnell