16

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?

3 Answers 3

11

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.
Sign up to request clarification or add additional context in comments.

Comments

8

Try specifying DataValueField of DropDownList1:

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

Comments

1
Convert.ToInt32(DropdownList1.selectedItem.value);

1 Comment

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.