Alex
Alex

Reputation: 9740

Bind DropDownList from List<Objects>

I have one list of objects

var listOfUsr = new List<User>();

listOfUsr = GetUserByAgentId("some_id");

if (listOfUsr != null)
{
    DropDownList.DataSource = listOfModels;
    //DropDownList.DataTextField = "how to set value_from User.Name ?";
    //DropDownList.DataValueField = "how to set value_from User.ID ?";
    DropDownList.DataBind();
}

How can I set text and value field from object properties?

Upvotes: 0

Views: 68

Answers (3)

Christos
Christos

Reputation: 53958

You could try this one:

DropDownList.DataTextField = "Name";
DropDownList.DataValueField = "ID";

I suppose, as it can be concluded from your comments, that an object of type User has two properties called Name and ID and these are the text and value correspondingly that you want to show.

Upvotes: 2

daniele3004
daniele3004

Reputation: 13970

Use a ComboBox and set DropDownStyle =ComboBoxStyle.DropDownList;

Try this code:

  var listOfUsr = new List<User>();

  listOfUsr = GetUserByAgentId("some_id");

  comboBox1.DropDownStyle =ComboBoxStyle.DropDownList;
  comboBox1.DataSource=lstOfUsr;
  comboBox1.DisplayMember="Description";

You can also drag an object of type BindingSource and use it in this mode:

var listOfUsr = new List<User>();

listOfUsr = GetUserByAgentId("some_id");

bindingSourceListOfObject.DataSource = lstOfUsr;

comboBox1.DropDownStyle =ComboBoxStyle.DropDownList;
comboBox1.DataSource=bindingSourceListOfObject;
comboBox1.DisplayMember="Description";

With BindingSource have many possibilities and flexibility on complex scenario.

Upvotes: 1

SpiderCode
SpiderCode

Reputation: 10122

You just have to set Column Name in DataTextField and DataValueField. In your case Name and ID are column names for your list object of user.

if (listOfUsr != null)
{
    DropDownList.DataSource = listOfModels;
    DropDownList.DataTextField = "Name";
    DropDownList.DataValueField = "ID";
    DropDownList.DataBind();
}

Upvotes: 2

Related Questions