DropDownList Part 2: Setting Default Value on First Page Load
In part one DropDownList Part 1: Bind a DataTable to A DropDownList we learned how to bind a DataTable to a DropDownList. In this tutorial we will learn to set the default value of the DropDownList control on the page's first load that is before there is a post back to the page. This behavior is commonly used when you want to default the drop down list to a particular selection. Such as the "United States" in a list of countries drop down list.
To set a default value in the DropDownList control follow the steps below.
1. Add the SetDefaultSelectItem method to the code behind file.
2. Add a condition to only set the default value on the first page load
To set a default value in the DropDownList control follow the steps below.
1. Add the SetDefaultSelectItem method to the code behind file.
protected void SetDefaultSelectItem(string txtSelect)
{
DropDownList1.Items.FindByText(txtSelect).Selected = true;
}
2. Add a condition to only set the default value on the first page load
protected void Page_Load(object sender, EventArgs e)3. If you run the application you will now see that "Seafood" is the default selection on the DropDownList control, when the page first load
{
if(!Page.IsPostBack)
{
BindCategoriesList();
SetDefaultSelectItem("Seafood");
}
}
Related Blogs:
- Bind a DataTable To A DropDownList
- (DropDownList) Setting Default Value on First Page Load
- Use The DropDownList Control To Populate GridView
- Bind DropDownList To A List Of Objects
Comments
Post a Comment