DropDownList and SqlDataReader

  • Thread starter Thread starter TOm
  • Start date Start date
T

TOm

How do I bind a SqlDataReader to a dropdownlist box?

I know how to construct a SqlDataReader dr and get the
values. Buit how do I bind it to a DropDownList box in C#?

This does not work

cboUsers.DataSource = dr;
cboUsers.Items.Clear();
cboUsers.DataTextField = dr.GetValue(1).ToString();
cboUsers.DataValueField = dr.GetValue(0).ToString();
cboUsers.DataBind();

Please advise.

Thanks

Tom
 
Hi TOm,

Try setting the DataTextField and the DateValueField properties of the
dropdownlist.

Cheers,
 
Yip! Setting the properties in the HTML workd but not in
the code behind. Thanks for that!

Now that I know how to add items to a dropdown, do you
what I'd need to do to set a specific item in the as the
default one selected?

Tom
 
Hi Tom,

Just set the desired SelectedIndex property in the control, now if you don't
know the index of the elem you need then you have to iterate on the
collection and set the correct index, see that you have a SelectedItem and
SelectedValue but they are read only.

Cheers,
 
Tom



This code will help you....

It gets a datareader then binds it to the dropdownlist using in quotes the

name of the columns for the datavaluefield and datatextfield.

Therefore you do not need to use

dr.GetValue(1).ToString();

instead use:

dr.DataValueField = "yourkeyfield - column name in the reader"

dr.DataTextField = "yourtextfield - column name in the reader"

Hope it helps

Kuv

------------

SqlConnection conn = new SqlConnection("database=northwind; server=(local);

user=sa; pwd=;");

conn.Open();

SqlDataReader dr;

SqlCommand cmd = new SqlCommand("Select * from

customers",conn);

dr = cmd.ExecuteReader();

dr1.DataSource = dr;

dr1.DataTextField = "contactname";

dr1.DataValueField = "customerid";

dr1.DataBind();
 
Kuv:

Many thanks

Tom
-----Original Message-----
Tom



This code will help you....

It gets a datareader then binds it to the dropdownlist using in quotes the

name of the columns for the datavaluefield and datatextfield.

Therefore you do not need to use

dr.GetValue(1).ToString();

instead use:

dr.DataValueField = "yourkeyfield - column name in the reader"

dr.DataTextField = "yourtextfield - column name in the reader"

Hope it helps

Kuv
("database=northwind; server=(local);
 
Back
Top