Mahesh KP
Mahesh KP

Reputation: 6446

Binding dropdownlist

I have got a requirement to bind a dropdownlist using db values.I gave that dropdownlist datasource as a list of class, ie ddlUser.datasource=List <User>;

The class user contains following properties UserID, Firstname and Lastname.

Its datavalue field is UserID.

I want to show the text of dropdown as a string ie Firstname+" " + Lastname.

Upvotes: 0

Views: 601

Answers (2)

PMC
PMC

Reputation: 4766

Couple of ways to do this, add a property to your user name FullName

public string FullName 
{ 
    get 
    {
        return String.Format("{0} {1}", Firstname, LastName);
    }
}

or use a foreach to create a list of listitem with id as the value and the concantaned name as the text.

List<ListItem> userList = new List<ListItem>();
foreach (User u in Users)
{                        
   userList.Add(new ListItem(String.Format("{0} {1}", u.Firstname, u.LastName), u.UserID ));
}

Upvotes: 1

user554180
user554180

Reputation:

override tostring method in User class so it's like this

public override string ToString()
{
   return Firstname + " " + Lastname;
}

When you bind make sure you have an populated list of users i.e.

List<User> list = new List<User>();
// populate list
ddlUser.DataSource = list;
ddlUser.DataBind();

Upvotes: 0

Related Questions