views:

1936

answers:

1

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

+5  A: 

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>");
patridge
addFirstItem(document.getElementById("yourListId"), "Select something", "-1"); is giving error saying that object expected
RBS
If that is the line generating the error, you need to actually have a list with ID="yourListId" (or change the ID used in getElementById). I was simply putting "yourListId" in as a placeholder. If it is a line within addFirstItem that is having the error, let me know.
patridge