Aikanáro
Aikanáro

Reputation: 849

How can I fill a drop down list with the result of a linq query dynamically?

I have two drop down list. The secod will change according the selected value in the first one.

This is what i'm trying, but is not working.

protected void ddTerritory_SelectedIndexChanged (object sender, EventArgs e)
{
    NorthwindDataContext bd = new NorthwindDataContext();

    var selectedTerritory =
        (from t in bd.EmployeeTerritories
         where t.TerritoryID == this.ddTerritory.SelectedValue
         select t).ToList();

    for (int i = 0; i < selectedTerritory .Count; i++)
    {
        this.ddTerrSelc.Items.Insert(i,
            new ListItem(territorioSeleccionado[0].ToString(), i.ToString()));
    }
}

I see some examples, but all of them were using a DataSet as the data source for the drop down list, and as you can see, I'm using linq to sql, so I think there have to be a way to do this without a dataset

Upvotes: 1

Views: 2212

Answers (1)

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79969

You didn't need to insert the result set by hand, you can do this instead:

var selectedTerritory =
            (from t in bd.EmployeeTerritories
             where t.TerritoryID == this.ddTerritory.SelectedValue
             select t).ToList();

this.ddTerrSelc.DataTextField = "Name";
this.ddTerrSelc.DataValueField = "ID";
this.ddTerrSelc.ItemsSource = selectedTerritory;

Upvotes: 1

Related Questions