How would I reset my asp:DropDownList
element (which has a runat="server"
) to index 0 every time the page is "reloaded" in Firefox (F5 is pressed)?
If you suggest using JavaScript, please note that
runat="server"
with JavaScriptIf this can be done using script on the .aspx
page then please explain.
put code in the Page_Load event to do this
protected void Page_Load(object sender, EventArgs e)
{
myDropDownList.SelectedIndex =0;
}
EDIT:
In response to your comments, If you have put the above logic inside of an if statement to check whether Page.IsPostback = false
, then the selected index will not be set back to 0 upon refresh (which performs a client postback). As an example to demonstrate this, here is a page with a dropdown list set to autopostback upon selection
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>My Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" >
</asp:DropDownList>
</div>
</form>
</body>
</html>
Here is the code behind
public partial class _Default : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
//Apologies for Dairy Produce inspired list
ddl.Items.Add(new ListItem("Cheese"));
ddl.Items.Add(new ListItem("Yoghurt"));
ddl.Items.Add(new ListItem("Milk"));
ddl.Items.Add(new ListItem("Butter"));
}
protected void Page_Load(object sender, EventArgs e)
{
//Run the Page with this in first, then comment out
//the if statement to leave only ddl.SelectedIndex = 0;
if (!Page.IsPostBack)
{
ddl.SelectedIndex = 0;
}
}
}
As will be demonstrated, when the page is originally ran, upon refresh, the selected index will be retained within the dropdown list; When the if
statement is commented out however, upon refresh, the selected index is set to 0 (which in this case is Cheese).
Just add this code to your Page_Load event :
if (myDropDown.Items.Count > 0)
{
myDropDown.Items[myDropDown.SelectedIndex].Selected = false;
myDropDown.Items[0].Selected = true;
}
In your script under code HTML:
B01 = document.getElementById('<%=me.yourID.clientid %>');
B01.selectedIndex = 0;
Happy Coding ^^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With