how can I bind the dataset to a dropdownlist, i want to use the field "product id" as the value, and "product name" as the label

i have a function to return the value from a sql statement "select * from product"

how can I bind the dataset to a dropdownlist, i want to use the field "product id" as  the value,  and "product name" as the  label
musclejackAsked:
Who is Participating?
 
tusharashahCommented:
You can bind it like following:

DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "ProductName";
DropDownList1.DataValueField = "ProductID";
DropDownList1.DataBind();

-tushar
0
 
AerosSagaCommented:
and if you ever needed it for a datareader:
'where dr is your datareader
 dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        Me.ddlAssignedTechnician.DataSource = dr
        Me.ddlAssignedTechnician.DataTextField = "LastName"
        Me.ddlAssignedTechnician.DataValueField = "TechnicianID"
        Me.ddlAssignedTechnician.DataBind()
0
 
daffodilsCommented:
tusharshah is right.. so is AerosSaga if you want to use a data reader..

Just remember to bind it within if(!IsPostBack).. block.. so that the data binding occurs only the first time the page loads, and not on every postback! If binding occurs on evey page load, you would lose the SelectedItem/SelectedIndex value.

if(!IsPostBack)
{
   DropDownList1.DataSource = ds;
   DropDownList1.DataTextField = "ProductName";
   DropDownList1.DataValueField = "ProductID";
   DropDownList1.DataBind();
}
0
 
jnhorstCommented:
Aeros and Daffodils are right on this.  Populating a drop down is always a straight forward query of data and so you definitely should be using a data reader rather than a dataset.  Datasets are for when you need to get data into a grid where you'll be sorting, updating, etc. the data.

John
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.