RBS
RBS

Reputation: 3851

How to set Custom Text into DropdownList in ASP.Net

I have dropdown list control in one of my application and when I add Items in it from database Its displaying the first Item into Dropdown list by default but I want to display someother text into this like "Select Item from the List" Is there any way I can do this .

Also Can you please help me setting the same value from javascript

Upvotes: 1

Views: 20384

Answers (2)

FluxEngine
FluxEngine

Reputation: 13290

Patridge answer is correct, however if you are using the asp method and still run into a problem, add the items tag to the listitem.

<asp:DropDownList AppendDataBoundItems="true" ID="yourListId" runat="server">
  <items>   
    <asp:ListItem Text="Select something" Value="-1">--Select Something--</asp:ListItem>
  </items>
</asp:DropDownList>

Upvotes: 0

patridge
patridge

Reputation: 26565

On the ASP.NET side of things, you can create the DropDownList with AppendDataBoundItems="true" and any items you bind to it will come after the default:

<asp:DropDownList AppendDataBoundItems="true" ID="yourListId" runat="server">
    <asp:ListItem Text="Select something" Value="-1" />
</asp:DropDownList>

As for doing the same thing completely in Javascript, you can do it with a function like this:

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 (there is probably something much cleaner, especially for creating a new option tag, but this works):

$("#yourListId option:first").before("<option value='-1'>Select something</option>");

Upvotes: 7

Related Questions