Question

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

Was it helpful?

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

OTHER TIPS

You're setting the actual value of 'name' as the DisplayMember, so unless you randomly get a value in 'name' set to the same text as a property then you'll never get it displayed.

You'd be better off just doing:

listBoxScripts.DisplayMember = "name";

Surely?

Try casting the dictionary element as a Script object

listBoxScripts.DisplayMember = ((Script)allScripts.scripts["Key"]).name.ToString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top