Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text from selected item in DropDownList asp.net

In the pageload i populate a dropdownlist 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 then try to set the text of a label on the same page to the selectetitem.text i only get the first item in the list, not the item i selected. I try to set the text by using a button like this:

protected void btnBuySoldierBuilding_Click(object sender, EventArgs e)
    {
        lblTestlabel.Text = ddlSoldierBuildings.SelectedItem.Text;
    }

the dropdownlist contains tree items, barracks, shooters range, and stable which i get from my database. Does the page load overwrite my selection when i click the button? How can i solve this?

like image 651
Twistar Avatar asked Dec 30 '25 22:12

Twistar


2 Answers

That's because your Page_Load is firing before your event handler.

Wrap your Page_Load initialization logic inside an if block where you check if your page is handling a postback or not by checking the Page.IsPostback property. If it's a postback, then your initialization logic won't fire and reset your drop down list.

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();
       }
    }
like image 59
David Hoerster Avatar answered Jan 02 '26 10:01

David Hoerster


Wrap the binding code above in an if (!Page.IsPostBack) { } block. Else you are losing your control state.

like image 23
Till Avatar answered Jan 02 '26 12:01

Till



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!