meeeeeeeeee
meeeeeeeeee

Reputation: 351

CheckedListBox Display Different String c#

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.

Upvotes: 3

Views: 1256

Answers (3)

Myles McDonnell
Myles McDonnell

Reputation: 13335

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.

Upvotes: 2

Fischermaen
Fischermaen

Reputation: 12458

Here is my suggestion for you. Create a data class for your backup folders like that:

public class BackupFolder
{
    private string folderPath;

    public BackupFolder(string folderPath)
    {
        this.folderPath = folderPath;
        FolderName = folderPath.Split(new[] { '\\' }).Last();
    }

    public string FolderName { get; private set; }
}

Then set a list of those files as DataSource for the CheckedListBox and set the DisplayMember to the property that contains the value as you want to display it. Like this:

var data = new BindingList<BackupFolder>();
data.Add(new BackupFolder("D:\\Data"));
checkedListBox1.DataSource = data;
checkedListBox1.DisplayMember = "FolderName";

Upvotes: 0

Rached N.
Rached N.

Reputation: 148

How are you getting the folders names, by FolderBrowserDialog, or it is manual input by the user?

Use .Split('\')

Upvotes: 0

Related Questions