如何从下拉列表中获取选定的值C#ASP.NET

时间:2017-04-03 01:51:33

标签: 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;
}

此结果始终获得值用户 Administartor 字符串。但是,它不是我想要的。我想从DropdownList1中的值中获得值 0 1 。怎么做?

3 个答案:

答案 0 :(得分:4)

尝试指定DropDownList1的DataValueField:

DropdownList1.DataSource = items;
DropdownList1.DataValueField = "Value";
DropdownList1.DataTextField = "Text";
DropdownList1.DataBind();

答案 1 :(得分:2)

一种方法是使用DropDownList SelectedItem Property获取selectedItem(ListItem),然后使用ListItem.Value Property获取ListItem的相应值}。

lblResult.Text = DropdownList1.SelectedItem.Value; // Value property Gets or sets the value associated with the ListItem.

答案 2 :(得分:0)

Convert.ToInt32(DropdownList1.selectedItem.value);