bind columns to dropdownlist

A

Andy Sutorius

How do you tell the dropdownlist datatextfield and datavaluefield to be
bound to specific columns using the following code?


private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
SqlConnection conn = new
SqlConnection("server=localhost;trusted_connection=yes;database=Test");
SqlCommand cmd = new SqlCommand("SELECT * FROM Dogs", conn);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
DropDownList1.DataSource = reader;
DropDownList1.DataTextField = ;
DropDownList1.DataValueField = ;
DropDownList1.DataBind();
}
catch (Exception ex)
{ Response.Write(ex.ToString()); }
finally
{ conn.Dispose(); }
}
}
 
A

Andy Sutorius

I figured it out. I needed a dataset and then I could set the datatextfield
and datavaluefield to the fields in the table. Below is the code I ended up
with.

private void Page_Load(object sender, System.EventArgs e)

{

if (!IsPostBack)

{

SqlConnection conn = new
SqlConnection("server=localhost;trusted_connection=yes;database=Test");

SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Dogs", conn);

DataSet ds = new DataSet();

da.Fill(ds, "Dogs");

try

{

conn.Open();

DropDownList1.DataSource = ds;

DropDownList1.DataTextField = "Breed";

DropDownList1.DataValueField = "ID";

DropDownList1.DataBind();

}

catch (Exception ex)

{ Response.Write(ex.ToString()); }

finally

{ conn.Dispose(); }

}

}
 

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,995
Messages
2,570,228
Members
46,817
Latest member
AdalbertoT

Latest Threads

Top