he creado un sitio web simple formulario web asp.net usando C #. tengo un código para mostrar datos en la lista desplegable cuando la página se carga así:
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(); }Lo llamo en la carga de la página:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DisplayData() } }trato de obtener valor de DropdownList1 en btnSubmit
protected void btnSubmit_Click(object sender, EventArgs e) { lblResult.Text = DropdownList1.SelectedValue; }este resultado siempre obtiene el valor de la cadena User o Administartor . pero, no quiero. Quiero obtener valor solo de los valores en DropdownList1 como 0 o 1 . ¿Como hacer esto?
Un enfoque es usar la propiedad DropDownList SelectedItem para obtener el elemento seleccionado ( ListItem ) y luego usar la propiedad ListItem.Value para obtener el valor correspondiente para ListItem .
lblResult.Text = DropdownList1.SelectedItem.Value; // Value property Gets or sets the value associated with the ListItem.Intente especificar DataValueField de DropDownList1:
DropdownList1.DataSource = items; DropdownList1.DataValueField = "Value"; DropdownList1.DataTextField = "Text"; DropdownList1.DataBind();Convert.ToInt32(DropdownList1.selectedItem.value);