I understand that this is an old thread, but Google presented this as the first option for this problem - with a fairly general search term.
In any case, the problems that I encountered, and how I solved it, are as follows. The problem will either arise, such as Brian Mines, for the following reasons:
- There are no elements in the DropDownList because the evaluation takes place before the list is bound.
- List linked but missing value
- Return value may be null
The problem I encountered, although it was not very clear, because I did not get errors in some other DropDowns with which I used the same method, was that when loading the page I tried to use this code to add an element to DropDownList:
drpNationality.Text = GlobalScript.CountDatabaseRecords("SELECT [nationality_desc] FROM [tbl_people] INNER JOIN [tbl_lkup_nationality] AS nationality ON [nationality] = [nationality_id] WHERE [person_id] ='" + Session["ID"] + "'");
And here is the DropDown HTML code (which contains the elements populated by the DataSource):
<label>Nationality:</label> <asp:DropDownList ID="drpNationality" runat="server" DataSourceID="Nationality_Datasource" DataTextField="nationality_desc" DataValueField="nationality_id"> </asp:DropDownList>
Now the problem was that the data was not bound to the control at boot time, when I tried to add elements to the code. Since I tried to pre-select the value from the database at startup for the user (who existed in the list), I was not too concerned if the item essentially appeared twice there.
So, my work was as follows.
I changed the code to the following, so the item was added to the DropDownList when the Load Event code was executed, and then selected:
var = GlobalScript.CountDatabaseRecords("SELECT [nationality] FROM [tbl_people] INNER JOIN [tbl_lkup_nationality] AS nationality ON [nationality] = [nationality_id] WHERE [person_id] ='" + Session["ID"] + "'"); drpNationality.Items.Add(var); drpNationality.Text = var;
But in order to ensure that the element that was selected in the code remains after the page is completely loaded and the DataSource is not overwritten, you must change the HTML to the following:
<label>Nationality:</label> <asp:DropDownList ID="drpNationality" runat="server" DataSourceID="Nationality_Datasource" DataTextField="nationality_desc" DataValueField="nationality_id" AppendDataBoundItems="True"> </asp:DropDownList>
Now, when the page loads, the value from the database should be preselected in the drop-down list, and all DataSource elements should also be added.
Hope this helps.