How to get selected value from C # ASP.NET dropdown

I created a simple asp.net website using C #. I have some code to display data in a dropdown on 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 this on page load:

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

      

I am trying to get value from DropdownList1 in btnSubmit

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

      

this result always gets the string User or Administartor . but I don't want that. I want to get the value only from the values โ€‹โ€‹in DropdownList1 as 0 or 1 . How to do it?

+3


source to share


2 answers


Try to specify DataValueField for DropDownList1:



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

      

+3


source


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 ListItem

.



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

      

+1


source







All Articles