ListControl.SelectedValue Propiedad

Definición

Obtiene el valor del elemento seleccionado en el control de lista o selecciona el elemento en el control de lista que contiene el valor especificado.

public:
 virtual property System::String ^ SelectedValue { System::String ^ get(); void set(System::String ^ value); };
[System.ComponentModel.Bindable(true)]
[System.ComponentModel.Browsable(false)]
public virtual string SelectedValue { get; set; }
[System.ComponentModel.Browsable(false)]
[System.ComponentModel.Bindable(true, System.ComponentModel.BindingDirection.TwoWay)]
[System.Web.UI.Themeable(false)]
public virtual string SelectedValue { get; set; }
[<System.ComponentModel.Bindable(true)>]
[<System.ComponentModel.Browsable(false)>]
member this.SelectedValue : string with get, set
[<System.ComponentModel.Browsable(false)>]
[<System.ComponentModel.Bindable(true, System.ComponentModel.BindingDirection.TwoWay)>]
[<System.Web.UI.Themeable(false)>]
member this.SelectedValue : string with get, set
Public Overridable Property SelectedValue As String

Valor de propiedad

String

Valor del elemento seleccionado en el control de lista. El valor predeterminado es una cadena vacía ("").

Atributos

Excepciones

El valor seleccionado no está en la lista de valores disponibles y estado de vista, o se ha cargado otro estado (se ha realizado un postback).

Ejemplos

En el ejemplo siguiente se muestra cómo usar la SelectedValue propiedad para seleccionar un elemento en un ListBox control. Observe que esta propiedad también se puede usar para recuperar el valor del elemento seleccionado.

Importante

Este ejemplo tiene un cuadro de texto que acepta datos proporcionados por el usuario, lo que puede suponer una amenaza para la seguridad. De forma predeterminada, ASP.NET Web Pages valida que los datos proporcionados por el usuario no incluyen elementos HTML ni de script. Para más información, consulte Información general sobre los ataques mediante scripts.


<%@ Page Language="C#" AutoEventWireup="True" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" > 

<head runat="server">
    <title> ListControl SelectedValue Example </title>
<script runat="server">

      void Button_Click(Object sender, EventArgs e)
      {

         // Perform this operation in a try-catch block in case the item is not found.
         try
         {
            List.SelectedValue = ItemTextBox.Text;
            MessageLabel.Text = "You selected " + List.SelectedValue + ".";
         }
         catch (Exception ex)
         {
            List.SelectedValue = null;
            MessageLabel.Text = "Item not found in ListBox control.";
         }
             
      }

   </script>

</head>

<body>

   <form id="form1" runat="server">

      <h3> ListControl SelectedValue Example </h3>
 
      <asp:ListBox ID="List"
           runat="server">

         <asp:ListItem>Item 1</asp:ListItem>
         <asp:ListItem>Item 2</asp:ListItem>
         <asp:ListItem>Item 3</asp:ListItem>
         <asp:ListItem>Item 4</asp:ListItem>

      </asp:ListBox>

      <hr />

      Enter the value of the item to select: <br />
      <asp:TextBox ID="ItemTextBox"
           MaxLength="6"
           Text="Item 1"
           runat="server"/>

        

      <asp:Button ID="SelectButton"
           Text="Select Item"
           OnClick="Button_Click"
           runat="server"/>

      <br /><br />

      <asp:Label ID="MessageLabel"
           runat="server"/>     

   </form>

</body>
</html>

<%@ Page Language="VB" AutoEventWireup="True" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" > 

<head runat="server">
    <title> ListControl SelectedValue Example </title>
<script runat="server">

      Sub Button_Click(sender As Object, e As EventArgs)

         ' Perform this operation in a try-catch block in case the item is not found.
         Try
   
            List.SelectedValue = ItemTextBox.Text
            MessageLabel.Text = "You selected " & List.SelectedValue + "."
        
         Catch ex As Exception
     
            List.SelectedValue = Nothing         
            MessageLabel.Text = "Item not found in ListBox control."
     
         End Try
             
      End Sub

   </script>

</head>

<body>

   <form id="form1" runat="server">

      <h3> ListControl SelectedValue Example </h3>
 
      <asp:ListBox ID="List"
           runat="server">

         <asp:ListItem>Item 1</asp:ListItem>
         <asp:ListItem>Item 2</asp:ListItem>
         <asp:ListItem>Item 3</asp:ListItem>
         <asp:ListItem>Item 4</asp:ListItem>

      </asp:ListBox>

      <hr />

      Enter the value of the item to select: <br />
      <asp:TextBox ID="ItemTextBox"
           MaxLength="6"
           Text="Item 1"
           runat="server"/>

        

      <asp:Button ID="SelectButton"
           Text="Select Item"
           OnClick="Button_Click"
           runat="server"/>

      <br /><br />

      <asp:Label ID="MessageLabel"
           runat="server"/>     

   </form>

</body>
</html>

Comentarios

Esta propiedad devuelve la Value propiedad del objeto seleccionado ListItem. La SelectedValue propiedad se usa normalmente para determinar el valor del elemento seleccionado en el control de lista. Si se seleccionan varios elementos, se devuelve el valor del elemento seleccionado con el índice más bajo. Si no se selecciona ningún elemento, se devuelve una cadena vacía ("").

La SelectedValue propiedad también se puede usar para seleccionar un elemento en el control de lista estableciendolo con el valor del elemento.

Esta propiedad no se puede establecer mediante temas o temas de la hoja de estilos. Para obtener más información, vea ThemeableAttribute y ASP.NET Temas y máscaras.

Cuando el valor seleccionado no está en la lista de valores disponibles y se realiza un postback, se produce una ArgumentOutOfRangeException excepción. En el ejemplo siguiente se muestra cómo capturar un valor no válido antes de que se produzca el postback:

Me.DropDownList1.Items.Add(New ListItem( Text="Hello", Value="1" ))
If DropDownList1.Items.FindByValue("2") IsNot Nothing Then
    Response.Write("Found")
End If
this.DropDownList1.Items.Add(new ListItem{ Text="Hello", Value="1" });
if(DropDownList1.Items.FindByValue("2") != null) {
    Response.Write("Found");
}

Se aplica a

Consulte también