Sunday, June 1, 2014


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" "">  
 <html xmlns="">  
 <head runat="server">  
   <form id="form1" runat="server">  
     <asp:DropDownList ID="DropDownList1" runat="server">  
       <asp:ListItem Selected="True" Value="1">Male</asp:ListItem>  
       <asp:ListItem Value="2">Female</asp:ListItem>  
     <br />  
     <br />  
     <asp:DropDownList ID="DropDownList2" runat="server">  
     <br />  
     <br />  
     <asp:Button ID="Button1" runat="server" 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 _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");  

No comments:

Post a Comment