Reputation: 10345
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);
}
Upvotes: 5
Views: 82432
Reputation: 52241
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
}
Upvotes: 14
Reputation: 38200
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
Upvotes: 4
Reputation: 33637
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
Upvotes: 0
Reputation: 14781
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.
Upvotes: 0