Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append two field values in combobox display member in C#

In my table, I have a field of firstname and lastname, now what I want is to set firstname and lastname as displaymember in a combobox, but I don't know how to do it.

Something like this

cmbEmployees.DataSource = GetEmployees();
//something like below line which doesn't work
cmbEmployees.DisplayMember = "lastname, first_name";     
cmbEmployees.ValueMember = "id";

How can I achieve this? So that both lastname and firstname will be displayed in the combobox

like image 640
MekeniKine Avatar asked Feb 04 '13 01:02

MekeniKine


2 Answers

This example will guide you how to do that without modifying your base class.

First, you can leave your DisplayMember with one property, let's say:

cmbEmployees.DisplayMember = "lastname";

Now, go to your form in a [Design] mode, right click on the ComboBox -> Properties.

In the top of the Properties window, click on Events (lightning icon),

look for Format in the events list below (under Property Changed) and type there some event name, let's say: ComboBoxFormat , and press Enter. You will see this:

private void ComboBoxFormat(object sender, ListControlConvertEventArgs e)
{

}

And now write these following lines inside:

private void ComboBoxFormat(object sender, ListControlConvertEventArgs e)
{
    // Assuming your class called Employee , and Firstname & Lastname are the fields
    string lastname = ((Employee)e.ListItem).Firstname;
    string firstname = ((Employee)e.ListItem).Lastname;
    e.Value = lastname + " " + firstname;
}

That's it ;)

like image 195
Eliran Kuta Avatar answered Sep 18 '22 20:09

Eliran Kuta


Let's say you had a class like this:

class Person
{
    public string FirstName
    {
        get;
        set;
    }

    public string LastName
    {
        get;
        set;
    }

    public string FullName
    {
        get
        {
            return LastName + ", " + FirstName;
        }
    }

    public Person(string firstname, string lastname)
    {
        FirstName = firstname;
        LastName = lastname;
    }
}

If you don't have a FullName property, just create one in the format you wish to display the name. Then set the DisplayMember equal to FullName.

like image 29
Mash Avatar answered Sep 21 '22 20:09

Mash