Adding Value to Dropdownlist

G

Guest

In ASP.NET 2.0 I have a dropdownlist populated from a sqldatasource. The
dropdownlist values are successfully populated from a database table. I would
like to add the value "Select Company" which will be the selected value when
the page loads. I attempted to use the code below to add "Select Company"
dynamically but it is not added. Only the values from the database are in the
dropdownlist. I also tried to added it to the dropdownlist collection in
Visual Studio 2005 but "Select Company" was not added to the dropdownlist.
How do I add a value to the dropdownlist that is not in the database? Thank
you.

Dim NewItem As ListItem

NewItem = New ListItem("Select Company", "0")

DropDownList_companies.Items.Add(NewItem)
 
G

Guest

Mike

Try

ddlGroup.Items.Clear()
ddlGroup.Items.Add("Select Company")
ddlGroup.AppendDataBoundItems = True

'The key is the appendDataBoundItems this will allow the added item to stay
when
the data source is bound to the dropdownlist it works best if you add the
item before the databinding so it is the first item.

'Create your datasource here
ddlGroup.DataSource = MyDatasource
ddlGroup.DataBind()
 
N

Norman Yuan

Another way, besides Jerry's:

After the DataBining (you may bind the data all at once by calling
Page.DataBinding() or call DataBinding on each control), you simply insert a
new ListItem at beginning of the list (Index=0):

''Bind data to the dropdownlist first
DropDownList_companies.DataSource=theSource
DropDownList_companies.DataBinding()

Dim NewItem As ListItem = New ListItem("Select Company", "0")
DropDownList_companies.Items.Insert(0, NewItem)
 
G

Guest

Thank for the reply Jerry and Norman.

I'm trying to do this the ASP.NET 2.0 way by not binding in the code behind
file. I'm using the sqldatasource control (asp:SqlDataSource) in the aspx
file. Can this be done without binding in the code behind file? Thanks.
 
M

Mike O

The first example using "AppendDataBoundItems" can be done in the Page_Load on a dropdownlist that uses SqlDataSource
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top