Will_G
Will_G

Reputation: 269

change first item dropdownlist

I got a Dropdownlist that is databind but I want to change the first value.
but this don't work

var Movies = Directory
                             .GetFiles(MapPath("~\\Movies\\" ), "*.mp4")
                             .Select(p => Path.GetFileNameWithoutExtension(p))
                             .ToArray();

                Dropdownlist1.DataSource = Movies;
                Dropdownlist1.DataBind();
                Dropdownlist1.Items[0].Value = "Choose one";

Upvotes: 1

Views: 1916

Answers (2)

Zo Has
Zo Has

Reputation: 13018

Just set AppendDataBoundItems property to true on your dropdownlist. Then add a new list item in your aspx code like

 <asp:DropDownList ID="ddlInstallTypes" runat="server" 
            DataSourceID="odsTreatyInstallTypes" DataTextField="DisplayText" AppendDataBoundItems="true"
            DataValueField="Value"> <asp:ListItem Text="- Select -" Value="0"></asp:ListItem>
        </asp:DropDownList>

This way a new list item will be added to the list on top.

Upvotes: 0

Adil
Adil

Reputation: 148110

You are probably trying to insert new value at zero index of dropdown items, you need to use Dropdownlist1.Items.Insert to add element at the first location.

Dropdownlist1.DataSource = Movies;
Dropdownlist1.DataBind();
Dropdownlist1.Items.Insert(0, new ListItem("Choose one", "Choose one"));

Upvotes: 1

Related Questions