0

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.

user838359
  • 173
  • 1
  • 5
  • 18

2 Answers2

3

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>
PhilPursglove
  • 12,511
  • 5
  • 46
  • 68
  • wow I did not know this one, if it works, question I linked in my answer was pointless!? – Davide Piras Sep 28 '11 at 22:29
  • @Davide I was just looking at your answer and thinking 'we can't **both** be right' :-) Bear in mind that when the DataSourceId is set declaratively in the markup, there is no explicit call to `DataBind`, it all happens automagically. – PhilPursglove Sep 28 '11 at 22:31
  • @Davide Have a look at the second answer in the question you linked to, it also talks about this property. – PhilPursglove Sep 28 '11 at 22:33
  • yeah that's true but still could be possible to call Insert in the Page_PreRender. if everything done purely from markup side and your solution works, all good. my solution and what I linked is valid for a code based binding/approach. – Davide Piras Sep 28 '11 at 22:33
0

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

Community
  • 1
  • 1
Davide Piras
  • 43,984
  • 10
  • 98
  • 147