Saturday, June 14, 2014

Retrieving selected Item text, value, and index of an 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.

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" "">  
 <html xmlns="">  
 <head runat="server">  
   <form id="form1" runat="server">  
     <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>  
     <br />  
     <br />  
     <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />  

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");  
         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