4 IsPostBack in ASP
4 IsPostBack in ASP
net
IsPostBack is a Page level property, that can be used to determine whether the page is
being loaded in response to a client postback, or if it is being loaded and accessed for the
first time.
In real time there are many situations where IsPostBack property is used.
A sample form that we will use for this example is shown below. The form has First Name,
Last Name and City fields.
WebForm4.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
// can add list items to drop down list using smart tag , the click on Edit Items
Click Add, add the data in Text and Value as either the same data as Text or number
such as 0,1,2…….
Once you finish adding all list items click ok.
When we add data in the above manner the values are not duplicated
because the data is loaded even before the page load event.
Or
Do the following
Copy and Paste the following code in the code behind file of the web form.
protected void Page_Load(object sender, EventArgs e)
{
LoadCityDropDownList();
}
public void LoadCityDropDownList()
{
ListItem li1 = new ListItem("London");
DropDownList1.Items.Add(li1);
When we add data in the above manner the values are duplicated because the data is
loaded on the occurrence of the page load event.
Look at the City DropDownList. The cities, (London, Sydney and Mumbai) are correctly
shown as expected.
So, every time you click the button, the city names are again added to the DropDownList.
We know that all ASP.NET server controls retain their state across postback.
So, the first time, when the webform load, the cities get correctly added to the
DropDownList and sent back to the client.
Now, when the client clicks the button control, and the webform is posted back to the
server for processing.
During this stage, the city names are retrieved from the viewstate and added to the
DropDownList.
So, in the Page_Load, call LoadCityDropDownList() method, if the request, is not a postback
request.
That is, only if the webform is being loaded and accessed for the first time.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCityDropDownList();
}
}