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