C# Can I display an Attribute of an Object in a Dictionary as ListControl.DisplayMember?

c#, dictionary, listcontrol

Solution

You can binding to `Value` and override `ToString` method in `Script` class.

private void setupDataSources()
{            
    BindingSource ketchup = new BindingSource(allScripts.scripts, null);
    listBoxScripts.DisplayMember = "Value";
    listBoxScripts.ValueMember = "Key";
    listBoxScripts.DataSource = ketchup;            
}

Script class:

class Script
{
    public string name { get; set; }

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

Problem

The aim is to see the list as a list of 'name's. Here's the dictionary: ``` class Scripts { public Dictionary<int, Script> scripts = new Dictionary<int, Script>(); ... } ``` Here's the attribute 'name' I'm after: ``` class Script { public string name { get; set; } ... } ``` And here's the problem: ``` public partial class MainForm : Form { Scripts allScripts; public MainForm() { InitializeComponent(); allScripts = new Scripts(); setupDataSources(); } private void setupDataSources() { BindingSource ketchup = new BindingSource(allScripts.scripts, null); //THIS LINE: listBoxScripts.DisplayMember = allScripts.scripts["Key"].name.ToString(); listBoxScripts.ValueMember = "Key"; listBoxScripts.DataSource = ketchup; } ... } ``` I just can't think how to make that line work! Your advice is much appreciated! Thanks

Original source