Sunday, June 1, 2014

DropDownList

If you are adding listitem objects to the dropdownlist in the Page_Load event, make sure you do only when the page is loaded for the first time. Otherwise, every time, you post the page back by clicking button the list items will be added again causing duplication.
Example to add list items when the page is loaded
WebForm1.aspx :-
 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="_16_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 Selected="True" Value="1">Male</asp:ListItem>  
       <asp:ListItem Value="2">Female</asp:ListItem>  
     </asp:DropDownList>  
     <br />  
     <br />  
     <asp:DropDownList ID="DropDownList2" runat="server">  
     </asp:DropDownList>  
     <br />  
     <br />  
     <asp:Button ID="Button1" runat="server" 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 _16_dropdownlist  
 {  
   public partial class WebForm1 : System.Web.UI.Page  
   {  
     protected void Page_Load(object sender, EventArgs e)  
     {  
       if (!IsPostBack)  
       {  
         ListItem city1 = new ListItem("London", "1");  
         ListItem city2 = new ListItem("Canada", "2");  
         ListItem city3 = new ListItem("Japan", "3");  
         DropDownList2.Items.Add(city1);  
         DropDownList2.Items.Add(city2);  
         DropDownList2.Items.Add(city3);  
       }  
     }  
   }  
 }  

No comments:

Post a Comment