armannvg
armannvg

Reputation: 1712

Databinding a combobox to a Collection

I have a normal asp.net combobox on my web page. The current version is databinding a a datatable object, but I want to change it so that it databinds to a Collection but I am getting errors.

I've tried using an ObjectDataSource, but they have CRUD commands that I don't need.

So the question is... How can I databind an asp.net combobx to a collection ? Do I need to convert it to a list (possibly time-consuming) or is there a better way ?

Upvotes: 0

Views: 608

Answers (4)

armannvg
armannvg

Reputation: 1712

Thank's for your answers.

The error I was getting was The DataSourceID of 'controlname' must be the ID of a control of type IDataSource

I was databinding as you suggested

this.combobox.DataSource = userCollection;
this.combobox.DataTextField = "Name";
this.combobox.DataValueField = "UserId";
this.combobox.DataBind();

But I figured out that the DataSourceID property had been set in the Designer View, so I removed that and everything began working normally :)

Upvotes: 0

JustLoren
JustLoren

Reputation: 3234

With an ASP.NET combobox you'll want to set the DataValueField and DataTextField fields as well.

cboBox.DataSource = collection;
cboBox.DataTextField = "Name";
cboBox.DataValueField = "ID";
cboBox.DataBind();

That should get your data to display how you want it.

Upvotes: 0

Jan Jongboom
Jan Jongboom

Reputation: 27312

Every object whose type inherits IEnumerable can be bound to any object that supports databinding, so just do

object.DataSource = collection;
object.DataBind();

and it will work fine.

Upvotes: 2

Sly
Sly

Reputation: 15217

You can always assign a collection to the data source property of combobox

Upvotes: 1

Related Questions