Saturday, June 14, 2014

Retrieving selected Item text, value, and index of an asp.net dropdownlist

DropDownList Selected Item
To retrieve
1. selected item Text :- DropDownList1.SelectedIndex.Text
2. selected item Value :- DropDownList1.SelectedIndex.value or DropDownList1.SelectedValue
3. selected item index :- DropDownList1.SelectedIndex

The SelectedIndex and SelectedValue properties of the Dropdownlist can also be used to have list item selected in the Dropdownlist.

Example:
WebForm1.aspx :-
 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="_21_dropdownlist.WebForm1" %>  
 <!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></title>  
 </head>  
 <body>  
   <form id="form1" runat="server">  
   <div>  
     <asp:DropDownList ID="DropDownList1" runat="server">  
       <asp:ListItem Value="-1">Select</asp:ListItem>  
       <asp:ListItem Value="1">Asia</asp:ListItem>  
       <asp:ListItem Value="2">Europe</asp:ListItem>  
       <asp:ListItem Value="3">Africa</asp:ListItem>  
     </asp:DropDownList>  
     <br />  
     <br />  
     <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />  
   </div>  
   </form>  
 </body>  
 </html>  

WebForm1.aspx.cs :-
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 namespace _21_dropdownlist  
 {  
   public partial class WebForm1 : System.Web.UI.Page  
   {  
     protected void Page_Load(object sender, EventArgs e)  
     {  
       if (!IsPostBack)//Only during be the Initial page load when the page first load  
       {  
         DropDownList1.SelectedIndex = 1; //Asia will be selected by default  
         //DropDownList1.SelectedValue = "1";  
       }  
     }  
     protected void Button1_Click(object sender, EventArgs e)  
     {  
       if (DropDownList1.SelectedValue == "-1")  
         Response.Write("Plese select the Country");  
       else  
       {  
         Response.Write("Text is "+DropDownList1.SelectedItem.Text+"<br/>");  
         Response.Write("Value is "+DropDownList1.SelectedItem.Value + "<br/>");  
         Response.Write("Index is "+DropDownList1.SelectedIndex + "<br/>");  
       }  
     }  
   }  
 }  

No comments:

Post a Comment