populate dropdownlist

2019-06-12 09:27发布

问题:

Hi i need to populate a dropdownlist. I designed a datasource and assigned it to dropdownlist. The dropdown populated correctly. But the problem is that i need to add a default value say "default" at the starting of the dropdownlist( and this value default is not in the database.

I did this :

 <asp:DropDownList ID="classInstructor" runat="server" DataSourceID="SqlDataSource3" 
                DataTextField="InstrName" DataValueField="InstrName">

        <asp:ListItem Value="Default" Text="Default" Selected="True"></asp:ListItem>


        </asp:DropDownList>

But default doesn't show up on dropdown. Probably, the way i did was wrong. Can u let me know the best way to handle this.

回答1:

Set the AppendDataBoundItems property to true on the dropdown list and the items from the data source will appear after any ListItems you add in the markup e.g.

<asp:DropDownList ID="classInstructor" runat="server" DataSourceID="SqlDataSource3" 
    DataTextField="InstrName" DataValueField="InstrName" AppendDataBoundItems="true">
    <asp:ListItem Value="Default" Text="Default" Selected="True"/>
</asp:DropDownList>


回答2:

you cannot use this approach if the DropDownList is bound to a datasource at runtime this Default item you have in the markup at design time will be washed away in the binding.

what you need to do is an Insert after the call to the DataBind() method.

see here for the examples and more comments on this: Asp.net - Add blank item at top of dropdownlist