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?
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.
Try specifying DataValueField of DropDownList1:
DropdownList1.DataSource = items;
DropdownList1.DataValueField = "Value";
DropdownList1.DataTextField = "Text";
DropdownList1.DataBind();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With