Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get Selected Value from Dropdown List C# ASP.NET

Tags:

c#

asp.net

i have created simple website asp.net webform using C#. i have code to display data in dropdownlist when page load like this:

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

I call it in page load:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DisplayData()
    } 
}

i try to get value from DropdownList1 in btnSubmit

protected void btnSubmit_Click(object sender, EventArgs e)
{
    lblResult.Text = DropdownList1.SelectedValue;
}

this result always get value User or Administartor string. but, it doesn't i want. I wanna get value just from the values in DropdownList1 as 0 or 1. How to do this?

like image 897
aminvincent Avatar asked Apr 03 '17 01:04

aminvincent


2 Answers

One approach is to use the DropDownList SelectedItem Property to get the selectedItem(ListItem), then use the ListItem.Value Property to get the corresponding value for the ListItem.

lblResult.Text = DropdownList1.SelectedItem.Value; // Value property Gets or sets the value associated with the ListItem.
like image 197
Ousmane D. Avatar answered Oct 05 '22 23:10

Ousmane D.


Try specifying DataValueField of DropDownList1:

DropdownList1.DataSource = items;
DropdownList1.DataValueField = "Value";
DropdownList1.DataTextField = "Text";
DropdownList1.DataBind();
like image 28
borkovski Avatar answered Oct 06 '22 00:10

borkovski