Text from selected item in DropDownList asp.net

喜你入骨 提交于 2019-12-10 21:32:42

问题


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.



来源:https://stackoverflow.com/questions/9889971/text-from-selected-item-in-dropdownlist-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!