Page.IsPostBack Property in ASP.Net ASPX

The Page class includes a property called the IsPostBack property, which you can use to detect whether the page has already been posted back to the server.

Because of View State, when you initialize a control property, you do not want to initialize the property every time a page loads. Because View State saves the state of control properties across page posts, you typically initialize a control property only once, when the page first loads.

you must use the IsPostBack property to detect whether or not the page has been posted.

<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
void Page_Load()
{
if (!Page.IsPostBack)
{
// Create collection of items
ArrayList items = new ArrayList();
items.Add(“India”);
items.Add(“USA”);
// Bind to DropDownList
lstCountry.DataSource = items;
lstCountry.DataBind();
}
}
protected void BtnSubmit_Click(object sender, EventArgs e)
{
lblMessage.Text = lstCountry.SelectedItem.Text;
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Show IsPostBack</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:DropDownList id=”lstCountry” Runat=”server” />
<asp:Button id=”BtnSubmit” Text=”Select” OnClick=”BtnSubmit_Click” Runat=”server” />
<br /><br />
You selected:<asp:Label id=”lblMessage” Runat=”server” />
</div>
</form>
</body>
</html>

Page_Load() event handler executes only once when the page first loads. When you post the page again, the IsPostBack property returns True and the code contained in the Page_Load() handler is skipped.
Tags: , ,
Hot on Web:


About author