[英]Not able to get the dropdown list selected value on button click in asp.net c#
[英]How to Get Selected Value from Dropdown List C# ASP.NET
我使用C#創建了簡單的網站asp.net webform。 我有代碼在頁面加載時在下拉列表中顯示數據,如下所示:
private void DisplayData()
{
List<ListItem> items = new List<ListItem>();
items.Add(new ListItem("User", "1"));
items.Add(new ListItem("Administrator", "0"));
DropdownList1.DataSource = items;
DropdownList1.DataBind();
}
我在頁面加載中調用它:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisplayData()
}
}
我試圖從btnSubmit中的DropdownList1獲取值
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblResult.Text = DropdownList1.SelectedValue;
}
此結果始終獲得值User或Administartor字符串。 但是,它不是我想要的。 我想從DropdownList1中的值得到的值為0或1 。 這該怎么做?
嘗試指定DropDownList1的DataValueField:
DropdownList1.DataSource = items;
DropdownList1.DataValueField = "Value";
DropdownList1.DataTextField = "Text";
DropdownList1.DataBind();
一種方法是使用DropDownList
SelectedItem屬性獲得selectedItem屬性( ListItem
),然后使用ListItem.Value屬性得到了相應的值ListItem
。
lblResult.Text = DropdownList1.SelectedItem.Value; // Value property Gets or sets the value associated with the ListItem.
Convert.ToInt32(DropdownList1.selectedItem.value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.