Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post Dec 10, 2010 11:08 AM by chandradev1
Dec 03, 2010 02:38 PM|LINK
How can I fill in a dropdownlist with data being pulled from a table? I scratched my head for 3 hours before I found a solution. I'd like to share it here just in case someone is also having a same question.
Suppose in my EmployeeTB table I have the following columns:
UniqueID, FirstName, LastName, Address, Phone
And I want to fill in a dropdownlist (in DESC order) with all employees name in format "FistName, LastName"
So suppose my EmployeeTB table has the following entries:
UniqueID FirstName LastName Address ect...
123456 Mary Janes ............
789098 Bill Miers ............
I want to fill in my dropdownlist with items in format:
Please select an employee name to begin
To fill in a dropdownlist automatically with data. Here is code for my dropdownlist:
runat="server" DataSourceID="SqlDataSource1" DataMember="DefaultView"
select an employee name to begin"></asp:ListItem>
[UniqueID], [FirstName]+', '+[LastName] AS 'FullName' FROM [EmployeeTB] ORDER BY [FullName]"></asp:SqlDataSource>
Notice I combine column FirstName and LastName and return it into 1 column named FullName. SQL syntax is:
SELECT column1+ ', ' +column2 AS "new_column"
Also notice I include UniqueID column in the SELECT query because I will need that value to populate the gridview with associated information pulled from the database for the selected name from the dropdownlist.
I added a static item "Please select an employee name to begin". It has value of 0 to make sure it always stay at the top and selected by default when the page is loaded at the first time. Also, when user select this item, nothing happens.
To populate the gridview the information of, like "Bill Miers", I put these lines in my dropdownlist1_SelectedIndexChanged() method.
string conn =
SqlConnection connect =
SqlCommand cmd =
* FROM timesheettb WHERE employeeid = '" + dropdownlist1.SelectedValue +
SqlDataReader data_reader = cmd.ExecuteReader();
GridView1.DataSource = data_reader;
Refer back to where I create the dropdownlist, I associated the DataValueField with UniqueID being pulled from the table from the
Hope someone will find this helpful.
Dec 10, 2010 11:08 AM|LINK
Use parameterise query to avoid sql injection