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
- How to get domain name information from a Domain using Python
- ModulenotFoundError: no module named 'debug_toolbar' -SOLUTION
- How to create superuser in django project hosted in cPanel without terminal
- CSS & images not loading in django admin | cpanel without terminal
- Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects
- How to sell domain name on Godaddy (2023)
- TemplateSyntaxError at / Could not parse the remainder: ' + 1' from 'forloop.counter0 + 1'
- urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0
Related Article