Jordan Foreman
Jordan Foreman

Reputation: 3888

Populating Gridview with DropDownList

I'm trying to make a gridview that shows details of a table based upon what year is selected in the dropdownlist above the gridview.

The dropdownlist.datasource consists of years in datetime form, and is populated from a Years table (where YearId is the primary key, but not the field that is shown) in the database. The gridview.datasource consists of items from the Items table (where YearId is a foreign key).

When the selection in the dropdownlist is changed, I need to get the selected item's YearId value, and change the datasource of the gridview to be something like this:

items.where(item => item.YearId == ((Year)dropdownlist.selecteditem).YearId)

Unfortunately, its never this simple, and

((Year)dropdownlist.selecteditem).YearId 

isn't valid. I cannot seem to cast the listitem as a Year object. Any ideas on how to do this?

[EDIT]

Here is how the dropdownlist is populated. If there is a better way of doing this, (and I'm sure there is) feel free to let me know!

dropdownlist.DataSource = DataContext.Years;
dropdownlist.DataValueField = "Year";
dropdownlist.DataBind();

Upvotes: 3

Views: 1193

Answers (2)

Marcus
Marcus

Reputation: 5457

You should do

dropdownlist.DataSource = DataContext.Years;
dropdownlist.DataValueField = "YearId";
dropdownList.DataTextField = "Year";
dropdownlist.DataBind();

Then use bonifaz's query.

Upvotes: 1

bonifaz
bonifaz

Reputation: 598

Why cast it to a Year at all? Have you tried this:

items.where(item => item.YearId == dropdownlist.SelectedValue)

Upvotes: 2

Related Questions