Tuesday, May 20, 2014

Use of IsPostBack property

Example :-
WebForm1.aspx :-
 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="video8_IsPostBackProperty.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>  
   <style type="text/css">  
     .style1  
     {  
       width: 114px;  
     }  
     .style2  
     {  
       width: 114px;  
       height: 23px;  
     }  
     .style3  
     {  
       height: 23px;  
     }  
   </style>  
 </head>  
 <body>  
   <form id="form1" runat="server">  
   <div>  
     <table style="width: 70%;">  
       <tr>  
         <td class="style1">  
           <asp:Label ID="Label1" runat="server" Text="First Name"></asp:Label>  
         </td>  
         <td>  
           <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
         </td>  
       </tr>  
       <tr>  
         <td class="style1">  
           <asp:Label ID="Label2" runat="server" Text="Last Name"></asp:Label>  
         </td>  
         <td>  
           <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
         </td>  
       </tr>  
       <tr>  
         <td class="style2">  
           <asp:Label ID="Label3" runat="server" Text="City"></asp:Label>  
         </td>  
         <td class="style3">  
           <asp:DropDownList ID="DropDownList1" runat="server">  
           </asp:DropDownList>  
         </td>  
       </tr>  
       <tr>  
         <td class="style1" colspan="1" rowspan="1">  
         </td>  
         <td colspan="1" rowspan="1">  
           <asp:Button ID="Button1" runat="server"   
             Text="Register Employee" />  
         </td>  
       </tr>  
     </table>  
     <br />  
   </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 video8_IsPostBackProperty  
 {  
   public partial class WebForm1 : System.Web.UI.Page  
   {  
     protected void Page_Load(object sender, EventArgs e)  
     {   
       if(!IsPostBack)          
       LoadCityDropDownList();  
       //Or disable the view state of the drop downlist as Enable View State  
       //Or DropDownList1.Items.Clear();LoadCityDropDownList();  
     }  
     public void LoadCityDropDownList()  
     {  
       ListItem li1 = new ListItem("London");  
       DropDownList1.Items.Add(li1);  
       ListItem li2 = new ListItem("Sydni");  
       DropDownList1.Items.Add(li2);  
       ListItem li3 = new ListItem("paris");  
       DropDownList1.Items.Add(li3);  
     }  
   }  
 }  

Every time you click the button dropdownlist items will duplicated. we can use the IsPostBack property to solve this problem.

No comments:

Post a Comment