Databinding drop-down-list component to datareader?

  • Thread starter Thread starter Lauchlan M
  • Start date Start date
L

Lauchlan M

Hi

I have a drop down list and I want to populate it from a datareader.

I have this code

<<
Connection.Open();
dtrHospitalList = Cmd_HospitalList.ExecuteReader();
lstHospital.DataSource = dtrHospitalList;
lstHospital.DataBind();
There are two problems with this: first I would need to specify which of the
fields from the data reader goes in to the text of the drop down list (in
this case this field is 'HospitalName') and which field goes in to the
selectedvalue value (in this case 'HospitalCode').

Secondly, it just doesn't like it anyway! <g> - it tells me "Exception
Details: System.ArgumentException: An invalid data source is being used for
lstHospital. A valid data source must implement either IListSource or
IEnumerable."

So what is the correct code to databind a drop-down-list to a datareader? Or
should I be using something else instead, eg a dataset filled by a
dataadapter?

Thanks!

Lauchlan M
 
I have a drop down list and I want to populate it from a datareader.
I have this code

<<
Connection.Open();
dtrHospitalList = Cmd_HospitalList.ExecuteReader();
lstHospital.DataSource = dtrHospitalList;
lstHospital.DataBind();

ok, modified the code to

<<
Connection.Open();
dtrHospitalList = Cmd_HospitalList.ExecuteReader();
lstHospital.DataSource = dtrHospitalList;
lstHospital.DataTextField = "HospitalName";
lstHospital.DataValueField = "HospitalCode";
lstHospital.DataBind();
but I still get the same error on the line setting the datasource.
it tells me "Exception
Details: System.ArgumentException: An invalid data source is being used for
lstHospital. A valid data source must implement either IListSource or
IEnumerable."

So what is the correct code to databind a drop-down-list to a datareader? Or
should I be using something else instead, eg a dataset filled by a
dataadapter?

Thanks!

Lauchlan M
 
I have this code
ok, modified the code to

<<
Connection.Open();
dtrHospitalList = Cmd_HospitalList.ExecuteReader();
lstHospital.DataSource = dtrHospitalList;
lstHospital.DataTextField = "HospitalName";
lstHospital.DataValueField = "HospitalCode";
lstHospital.DataBind();

ok, modified it to use a dataset filled by a dataadapter and that works. So
is it not possible to databind it from a datareader, only from a dataset?

Lauchlan M
 
I've been having the same problem...and couldn't find anything on using a
datareader. I've a multi resultset in the dr, so the following is a
workaround to setting the value in code rather than in the HTML control
property:

While sqldr.Read
li = New ListItem
li.Text = CStr(sqldr.Item(1))
li.Value = CStr(sqldr.Item(0))
ddl.Items.Add(li)
End While

HTH

Bob
 
Back
Top