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

StackOverflow https://stackoverflow.com/questions/15817739

  •  01-04-2022
  •  | 
  •  

Вопрос

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

Это было полезно?

Решение

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

Другие советы

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();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top