Appending to a dropdown list

M

Maziar Aflatoun

Hi everyone,

I have dropdown list which I populate using ddl.DataBind(). However, I like
to initially add another DataValueField and DataTextField to the begining of
my dropdown list options. So that the end result would be my options in the
dropdown list + the ones read from the database table.

Ex.
ddlOwnerID.Items.Add("All"); // I like to add all as the first option.
ddlOwnerID.DataValueField = "OwnerID";
ddlOwnerID.DataTextField = "Username";

ReadSQL = "SELECT * FROM UserInfo";
SqlCommand Cmd = new SqlCommand(ReadSQL, Conn);
SqlDataReader rdr = Cmd.ExecuteReader();
ddlOwnerID.DataSource = rdr;
ddlOwnerID.DataBind();

Is that possible?

Thank you
Maz
 
D

David Wier

if you want to populate the extra item(s) after the databind - no
problem - -
just do something like:
Dim liItem as ListItem=New ListItem("text", "value")
MyDDL.Items.Insert(0, liItem)

This adds the item specifically to the top of the list

if you already have it populated, then, just instead of doing a ddl.DataBind
(vb.net) -

While sqlDataReader.Read
ddl.Items.Add(liItem)
end While

--

David Wier
MCP, MVP ASP.NET, ASPInsider
http://aspnet101.com
http://aspexpress.com
 
K

Kevin Spencer

Hi Maziar,

The problem is that you can't go both ways at the same time. You can add
Items to the DropDown, OR you can DataBind. You can't do both. So, you have
2 choices:

1. Use a DataTable instead of a DataReader. Perform your query, then insert
a new row at the beginning, with the additional option in it. After that,
DataBind to the DataTable.
2. Don't use DataBinding. Just add all the Items.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
I get paid good money to
solve puzzles for a living
 
D

David Jessee

Um....yes you can. databind it and then manually insert a new item at index
0, as shown in Mr. Weir's response.
Or you can insert the new item and then data bind it.
Or, what I do is create the default "--Select One--" item in the designer
and then databind it. databinding adds data to the dropdown, it doesn't
delete existing data
 
M

Maziar Aflatoun

I tried the first suggestion by David Wier and it worked :)

Thank you all
Maz.
 

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

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,120
Latest member
ShelaWalli
Top