MekeniKine MekeniKine - 1 month ago 8
C# Question

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

Answer

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.

Comments