简体   繁体   中英

How can I get the selected item of a dropdownlist, the first time my page loads?

I'm looking for a solution to get the first selected item in a DropDownList. And I want to get it when the page loads for the first time.

Thank you in advance.

Edit: I call this method at the Load-event but ddlNiveau2 remains empty. I think that ddlNiveau1.SelectedValue isn't accessed.

public void FillListNiveau2()
{
    ddlNiveau2.Items.Clear();
    foreach (var item in dBAL.GetListNiveau2(ddlNiveau1.SelectedValue))
    {
        ddlNiveau2.Items.Add(item.ToString());
    }
    RemoveDuplicateItems(ddlNiveau2);
}

There is a DataBound event , which fires after the data is bound to the dropdown. As you are assigning the dataSource to your dropdown you need selected item after all the rows binded to dropdown

protected void DropDownList1_DataBound(object sender, EventArgs e)
{
    DropDownList1.SelectedValue // store it in some variable
}

You can get the Selected Value like

string selected = drp.SelectedItem.Text;

Or

string selected = drp.SelectedItem.Value;

When the page is loaded the first value is shown Selected unless you set it by specifying the SelectedIndex or by Text/Value

Write the following code in the Page_Load event handler:

if (!Page.IsPostBack)
{

    // Load list items ..
    dropDownList.SelectedIndex = 0;

}

Refer to DropDownList class form more info.

When the page loads first time, there is no selected value in drop down until your code sets it using dropdown.SelectedValue property. This is the first time the page is loading and user has not interacted with the drop down yet , so it doesn't make sense to get the selected value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM