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);
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
}
Method 2
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
Method 3
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.
Method 4
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0