Wednesday, March 21, 2012

populating a drop down list with information from a database

Hello,
I am using C# and want to dynamically populate a drop down list with information from my database. I can do this effectively by data binding to the drop down list.

customerInfo.DataSource = aDataSet;
customerInfo.DataValueField = "licence_No";
customerInfo.DataTextField = "licence_No";
customerInfo.DataBind();

customer.Info is the name of my DDL. This does populate my DDL. However there is a big problem. If I try and get the selectedItem value from the DDL it is always equal to the first item in DDL, and therefore my DDL is useless.
Any suggestions, its been causing me alot of problems.Post the code you are using to get the selectedItem. Also, where in your code are you trying to get the selectedItem - after a certain event? When is the DropDownList populated? It probably should be populated once, when ! Page.IsPostBack()...

cjmaxey
The code I am using to get the selected item is:


string selection = customerInfo.SelectedItem.ToString();

I am trying to get the selected item when a button is clicked. The drop down list is populated on page load.
Thanks for the help.
shannon_rider,

Be sure that the Dropdownlist is populated within Page_Load() within the following:


if ( ! Page.IsPostBack() )
{
// populate database
} // end if - Not Page PostBack

It may be that that the DropDownList is getting re-populated before the SelectedItem is found and, therefore, being reset to the first item.

Also, you may want to use one of the following depending on whether you want the text or the value (in your case, I believe they are the same):


string selection = customerInfo.SelectedItem.Value.ToString();
string selection = customerInfo.SelectedItem.Text.ToString();

Hope this helps,

cjmaxey
Thanks,
That advice has worked. I appreciate you taking the time to help.
I'll take that lesson on board.

0 comments:

Post a Comment