Craig
Craig

Reputation: 18684

Display object property in ComboBox

I have a custom object which holds details about a project resource. Properties are PersonName, Position and Id If the resource isn't filled, PersonName is set to 'Unassigned'.

To add an object to a Combobox, I do:

var avail = s.GetUnassignedPrintRoles(SprintId);
foreach (var o in avail)
{
    cmbRoles.Items.Add(o);
}

This is fine when displaying a list of resources. My object has an overridden ToString() method:

public override string ToString()
{
    if(AssignedPerson != null)
        return ResourceType + " - " + AssignedPerson.Firstname + " " + AssignedPerson.Surname;
    return "Unassigned";
}

But, I have a screen that shows a list of roles that are not assigned. So, I get a list, where the Person is NULL.

But, I want to display the 'Role' in the ComboBox.

But, my object's ToString shows 'Unassigned'. How can I make it display the Role property? Is there a way to save the object in the Combobox item, but display a different property in the display, other than what I have set in the ToString override?

Upvotes: 2

Views: 4956

Answers (4)

Alaa Jabre
Alaa Jabre

Reputation: 1883

You can remove ToString() altogether by using read-only property:

public string FullInfo
{
    get
    {
       return ResourceType + " - " + AssignedPerson.Firstname + " " + AssignedPerson.Surname;
    }
}

then

 comboBox.DisplayMember = "FullInfo";
 comboBox.ValueMember = "Id";
 comboBox.DataSource = avail;

and you can do any kind of properties like this.

Upvotes: 1

Kestami
Kestami

Reputation: 2073

With regards to my comment, it might be needed to set the DisplayMember and ValueMember properties of the ComboBox, like so;

cmbRoles.DisplayMember = "Role";
cmbRoles.ValueMember = "Id";
cmbRoles.DataSource = avail;

This way your ComboBox will Display the role, but the underlying data will be the ID, So when you select via the SelectedValue property, you'll get the ID.

Upvotes: 6

zey
zey

Reputation: 6105

Add this ,

private void InitializeComponent()
    {
      cmbRoles.ValueMember = "id"; 
      cmbRoles.DisplayMember = "discription";
    }

Upvotes: 1

Steven Jennings
Steven Jennings

Reputation: 56

Have you tried using the DisplayMember property to distinguish the displayed value and the actual value? If you do that, you should be able to set the Role as the displayed entry on the combobox.

cmbRoles.DisplayMember = "" + Role;
cmbRoles.ValueMember = "Id";
cmbRoles.DataSource = avail;

I'm not sure what Role is in your code but you should be able to get the gist from that.

Upvotes: 1

Related Questions