Databound drop down list - initial value

后端 未结 8 1888
小蘑菇
小蘑菇 2020-12-24 03:21

How do I set the initial value of a databound drop down list in ASP.NET?

For instance, I want the values, but the first value to display should be -- Select One ---

8条回答
  •  眼角桃花
    2020-12-24 03:56

    I know this is old, but a combination of these ideas leads to a very elegant solution:

    Keep all the default property settings for the DropDownList (AppendDataBoundItems=false, Items empty). Then handle the DataBound event like this:

    protected void dropdown_DataBound(object sender, EventArgs e)
    {
        DropDownList list = sender as DropDownList;
        if (list != null)
            list.Items.Insert(0, "--Select One--");
    }
    

    The icing on the cake is that this one handler can be shared by any number of DropDownList objects, or even put into a general-purpose utility library for all your projects.

提交回复
热议问题