• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2005
  • Last Modified:

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
0
musclejack
Asked:
musclejack
1 Solution
 
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

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Tackle projects and never again get stuck behind a technical roadblock.
Join Now