Text from selected item in DropDownList asp.net

2019-07-04 23:23发布

问题:

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?

回答1:

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();
       }
    }


回答2:

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