In this post we are going to see about Page.IsPostBack Property, which we can use to detect
whether the page has already been posted back to the server.
In asp.net, when we initialize a control property, then we do need to initialize the control property every time a page loads.
Because View State saves the state of control properties across page posts, we typically initialize a control property only once,
when the page first loads.
Many controls do not work correctly if we reinitialize the properties of the control with
each page load. In these cases, we must use the IsPostBack property to detect whether the page has been posted.
ShowIsPostBack.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="ShowIsPostBack.aspx.cs"
Inherits="BlogSite.aspnet.Example.ShowIsPostBack" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Show IsPostBack</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlList" runat="server" />
<asp:Button ID="btnSelect" Text="Select" OnClick="btnSelect_Click"
runat="server" />
<br /> <br />
You selected:
<asp:Label ID="lblMsg" runat="server" />
</div>
</form>
</body>
</html>
ShowIsPostBack.aspx.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace BlogSite.aspnet.Example
{
public partial class ShowIsPostBack : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Create collection of items
ArrayList items = new ArrayList();
items.Add("Banana");
items.Add("Apples");
items.Add("Oranges");
items.Add("Mango");
// Bind to DropDownList
ddlList.DataSource = items;
ddlList.DataBind();
}
}
protected void btnSelect_Click(object sender, EventArgs e)
{
lblMsg.Text = ddlList.SelectedItem.Text;
}
}
}
Output:
When the code in the Page_Load() event handler executes only once when the
page first loads. When we post the page again, the IsPostBack property returns True and
the code contained in the Page_Load() handler is skipped.
If we remove the IsPostBack check from the Page_Load() method, we get a strange
result. The DropDownList always displays its first item as the selected item. Binding the
DropDownList to a collection of items reinitializes the DropDownList control. Therefore,
we want to bind the DropDownList control only once, when the page first loads.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.