In this example, I used dropdownlist and button, I binded dropdownlist with countries name on the page load without checking condition IsPostBack.
protected void Page_Load(object sender, EventArgs e)
{
LoadCountryDropDownList();
}
When I click the button notice countries’ names in the dropdownlist are duplicated. So if I repeatedly click on the button the country names are again added to the dropdownlist because of viewstate restoration.
countries name duplicating on button click event
In order to prevent from that we should use IsPostBack property.It is a page level property is used to determine whether the page is on its initial load or not.
if (!IsPostBack)
{
LoadCountryDropDownList();
}
Example:
Step 1: Copy and paste the following code.
WebControls.aspx:
<table style="font-family: Arial">
<tr>
<td colspan="2"><b>Customer Details Form</b></td>
</tr>
<tr>
<td>First Name: </td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Last Name: </td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Country:</td>
<td>
<asp:DropDownList ID="ddlCountry" runat="server">
</asp:DropDownList>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Register Customer" />
</td>
</tr>
</table>
WebControls.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCountryDropDownList();
}
}
public void LoadCountryDropDownList()
{
ListItem list1 = new ListItem("U.S");
ddlCountry.Items.Add(list1);
ListItem list2 = new ListItem("England");
ddlCountry.Items.Add(list2);
ListItem list3 = new ListItem("South Africa");
ddlCountry.Items.Add(list3);
ListItem list4 = new ListItem("Japan");
ddlCountry.Items.Add(list4);
ListItem list5 = new ListItem("China");
ddlCountry.Items.Add(list5);
ListItem list6 = new ListItem("India");
ddlCountry.Items.Add(list6);
}
protected void Button1_Click(object sender, EventArgs e)
{
}
Output:
Dropdownlist loading properly on button click,
Post your comments / questions
Recent Article
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
- The request was aborted: Could not create SSL/TLS secure channel -Error in Asp.net
Related Article