Wednesday 18 January 2012

first text as a custom in dropdown in c#.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 .

 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>"

No comments:

Post a Comment