Reputation: 101
I have a dropdown list which contains a number of items. I added a default list item to the dropdown.
For example, I have 4 list items in the dropdown:
I want to add a default list item of: please select item, which is not displayed in all list items in the dropdown.
How is this possible?
Upvotes: 0
Views: 1046
Reputation: 11844
You can write like follows
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex < 0)
{
DropDownList1.Text = "Please Select Item";
}
else
{
DropDownList1.Text = DropDownList1.SelectedValue;
}
}
EDIT:
The above code will display the "Please Select Item" only when the index of dd becomes lessthan 0 (i.e., when nothing selected), to test this at page_Load event make the index of dd to -1.
Upvotes: 0
Reputation: 1364
If you're adding the "Select One" item to the drop down from a reference table in a database (i.e. databinding) make sure to set the
AppendDataBoundItems="true" so that the form will append the new item BEFORE performing a databind.
One of my drop downs looks like this. It uses a datasource.
<asp:DropDownList ID="ddPackageStatus" runat="server" Width="200px"
AppendDataBoundItems="true" BackColor="White" Font-Size="10px"
DataSourceID="sdsPackageStatus"
DataTextField="PackageStatus" DataValueField="PackageStatus">
<asp:ListItem Text="Select One" Value=""></asp:ListItem>
</asp:DropDownList>
Upvotes: 1
Reputation: 2033
I have done this before, this is too simple thing
private void BindCountryList()
{
List<Country> list = GetCountryList();
list.Insert(0, new Country { CountryName = "Please select" });
ddCountry.DataSource = list;
ddCountry.DataTextField = "CountryName";
ddCountry.DataValueField = "CountryName";
ddCountry.DataBind();
}
Upvotes: 0
Reputation: 9415
You need to make sure the item you want as the default is in the list. This means you will need to add an item called 'Please select item' to the drop down list.
Upvotes: 0