Monday, June 9, 2008

postback [C# ASP.NET VS2005]

I have often heard this term, so I thought it might be useful if I add some notes to remind me. Postback is a condition when a web page send data to itself as a target from the form action. The Page know whether it is postback or not from its property : bool Page.IsPostBack. If it return true then it is postback.

Few notes about postback related to DropDownList component. I add the following code in my website to fill the drop down list with number from 15-30. The result for the following code is a DropDownList filled with empty string as it selected value and number from 15-30.
protected void Page_Load(object sender, EventArgs e)
{
#region Fill Age Dropdownlist
ddlAge.Items.Clear();
ddlAge.Items.Add("");
for (int i = 15; i <= 30; i++)
{
ddlAge.Items.Add(i.ToString());
}
#endregion
}
Assuming that I put this DropDownList named ddlAge in a form and submit it to itself to make a postback condition. The result is whatever value I choose in the ddlAge and then submit it, it always show empty string value. Why is that? Because the code to fill ddlAge is always run, regardless it is postback or not, so it will always fill again after the form submit to itself and the default value is always empty string. How do we solve it? We must check whether it is postback or not, if it is, then no need to run code for filling the ddlAge again. See the following code.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
#region Fill Age Dropdownlist
ddlAge.Items.Clear();
ddlAge.Items.Add("");
for (int i = 15; i <= 30; i++)
{
ddlAge.Items.Add(i.ToString());
}
#endregion
}
}
Kindly refer to other references :

No comments: