DropdownList reset to index 0 at boot

How would I reset my asp:DropDownListelement (which has runat="server") to index 0 every time the page "reloads" in Firefox (F5 is pressed)?

If you suggest using JavaScript, please note that

  • I do not use the form
  • I don't know how to access elements with runat="server"with JavaScript

If this can be done using the script on the page .aspx, please explain.

+3
source share
4 answers

enter the code in Page_Load for this

protected void Page_Load(object sender, EventArgs e)
{    
    myDropDownList.SelectedIndex =0;
}

EDIT:

, if, , Page.IsPostback = false, 0 ( ). , , ,

<%@ 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>

,

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;
        }
    }
}

, , ; , if , 0 ( ).

+7

Page_Load:

if (myDropDown.Items.Count > 0)
{
    myDropDown.Items[myDropDown.SelectedIndex].Selected = false;
    myDropDown.Items[0].Selected = true;
}
+1

script HTML:

B01 = document.getElementById('<%=me.yourID.clientid %>');
B01.selectedIndex = 0;

^^

+1

Stop Firefox from saving the viewstate and re-filling the form:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Browser.Browser == "Firefox")
            Form.Attributes.Add("autocomplete", "off");
    }
+1
source

Source: https://habr.com/ru/post/1705194/


All Articles