Text from selected item in DropDownList asp.net
In pageload, I populate a dropdown like this:
protected void Page_Load(object sender, EventArgs e)
{
string buildingTypeSoldier = "soldier";
var soldierBuilding = from b in dc.Buildings
where b.buildingtype == buildingTypeSoldier
select b.buildingname;
ddlSoldierBuildings.DataSource =soldierBuilding;
ddlSoldierBuildings.DataBind();
}
But when I try to set the label text on the same page in selectetitem.text, I only get the first item in the list, not the selected item. I am trying to set text using the following button:
protected void btnBuySoldierBuilding_Click(object sender, EventArgs e)
{
lblTestlabel.Text = ddlSoldierBuildings.SelectedItem.Text;
}
the dropdown contains the tree, barracks, arrows, and stable items which I get from my database. Does the page load reload when I click the button? How can I solve this?
source to share
This is because yours is being Page_Load
run before your event handler.
Wrap your initialization logic Page_Load
inside an if block where you check if your page is handling the backlink or not by checking the property Page.IsPostback
. If it's a postback then your initialization logic won't run and reset the dropdown.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback){
string buildingTypeSoldier = "soldier";
var soldierBuilding = from b in dc.Buildings
where b.buildingtype == buildingTypeSoldier
select b.buildingname;
ddlSoldierBuildings.DataSource =soldierBuilding;
ddlSoldierBuildings.DataBind();
}
}
source to share