How to customize custom text in DropdownList in ASP.Net
I have a dropdown control in one of my applications and when I add items from the database to it. It shows the first item in the dropdown by default, but I want to display some other text like "Select item from list". I can do it.
Also you can help me to set the same value from javascript
source to share
On the ASP.NET side, you can create a DropDownList with AppendDataBoundItems = "true" and any objects you bind to it with will appear by default:
<asp:DropDownList AppendDataBoundItems="true" ID="yourListId" runat="server">
<asp:ListItem Text="Select something" Value="-1" />
</asp:DropDownList>
As for completely doing the same thing in Javascript, you can do it with the following function:
function addFirstItem(list, text, value)
{
var newOption = document.createElement("option");
newOption.text = text;
newOption.value = value;
list.options.add(newOption);
}
addFirstItem(document.getElementById("yourListId"), "Select something", "-1");
Or with jQuery (maybe something much cleaner, especially for creating a new option tag, but that works):
$("#yourListId option:first").before("<option value='-1'>Select something</option>");
source to share
The patch answer is correct, however, if you are using the asp method and still face the problem, add the items tag to the list.
<asp:DropDownList AppendDataBoundItems="true" ID="yourListId" runat="server">
<items>
<asp:ListItem Text="Select something" Value="-1">--Select Something--</asp:ListItem>
</items>
</asp:DropDownList>
source to share