从DropDownList中asp.net所选项目的文本 [英] Text from selected item in DropDownList asp.net

查看:108
本文介绍了从DropDownList中asp.net所选项目的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在页面加载我填充一个DropDownList是这样的:

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

但是,当我再尝试在同一页面上设置标签的文本到selectetitem.text我只在列表中得到第一个项目,没有项目,我选择。我尝试使用一个按钮这样的设置文本:

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

DropDownList中含有树项目,营房,射击范围,稳定这是我从我的数据库中获取。是否页面加载覆盖我的选择,当我点击按钮?我怎样才能解决这个问题?

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?

推荐答案

这是因为你的的Page_Load 是事件处理程序之前发射。

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

裹在里面你的的Page_Load 初始化逻辑,如果块,你检查你的网页是处理回发或不通过检查的 Page.IsPostback 属性 。如果它是一个回传,那么你的初始化逻辑将不触发和重置您的下拉列表中。

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

这篇关于从DropDownList中asp.net所选项目的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆