简体   繁体   中英

DataSource, bind more then 1 value

I want to bind more then 1 columns to drop down list, so that I can get the column values when user clicks a button,

    ddlListMine.DataSource = GetSomeChickens();
    ddListMine.DataTextField = "ChickenName";
    ddListMine.DataValueField= "NumberOfEggsChickenLay";
    ddListMine.Items.Insert(0, new ListItem("Please Please Please Select....", "0"));
    ddListMine.DataBind();

I have another column "ChickenType", which I want to access in Selected Index change column.

GetSomeChickens() ; returns 6 columns, including ChickenName , NumberOfEggsChickenLay , ChickenType and so on...

Edit

Off course, I can call database again in selected index change method, but there must be a way around i think

The DropDownList doesn't hold the entire object during the binding, only the Text and Value as defined by DataTextField and DataValueField.

In order to get a selected object back, you can have a method to get the ChickenType by passing the ChickenName using Linq like this.

List<Chicken> Chickens = GetSomeChickens();
Var Chicken= Chickens.FirstOrDefault(c => c.ChickenName== ddlListMine.SelectedItem.Text);
if(Chicken!= null)
{
  string ChickenType = Chicken.ChickenType ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM