Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to populate a DropDownList from a database?

I am populating a DropDownList from a SQL Server database as shown below. It works fine, but I'm not sure it's a good way. Can someone shed some light on this method, and give some improvements?

private void LoadSubjects() {     ddlSubjects.Items.Clear();     string selectSQL = "SELECT SubjectID,SubjectName FROM Students.dbo.Subjects";      SqlConnection con = new SqlConnection(connectionString);     SqlCommand cmd = new SqlCommand(selectSQL, con);     SqlDataReader reader;      try     {         ListItem newItem = new ListItem();         newItem.Text = "<Select Subject>";         newItem.Value = "0";         ddlSubjects.Items.Add(newItem);          con.Open();         reader = cmd.ExecuteReader();         while (reader.Read())         {             newItem = new ListItem();             newItem.Text = reader["SubjectName"].ToString();             newItem.Value = reader["SubjectID"].ToString();             ddlSubjects.Items.Add(newItem);         }         reader.Close();     }     catch (Exception err)     {         //TODO     }     finally     {         con.Close();     } } 
like image 810
softwarematter Avatar asked Aug 29 '11 07:08

softwarematter


People also ask

How do you bind multiple values in a DropDownList from the database?

SqlCommand cmd = new SqlCommand("select * from UserDetail where id = '" + DropDownList1. SelectedValue + "'", con); SqlDataAdapter Adpt = new SqlDataAdapter(cmd); DataTable dt = new DataTable();

How do you create a DropDownList in SQL Server?

Double-click the list box, drop-down list box, or combo box control that you want to populate. Click the Data tab. Under List box entries, click Look up values from an external data source. In the Data Source list, click the data source that you want to use.


2 Answers

You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).

For example, if you wanted to use a DataTable:

ddlSubject.DataSource = subjectsTable; ddlSubject.DataTextField = "SubjectNamne"; ddlSubject.DataValueField = "SubjectID"; ddlSubject.DataBind(); 

EDIT - More complete example

private void LoadSubjects() {      DataTable subjects = new DataTable();      using (SqlConnection con = new SqlConnection(connectionString))     {          try         {             SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);             adapter.Fill(subjects);              ddlSubject.DataSource = subjects;             ddlSubject.DataTextField = "SubjectNamne";             ddlSubject.DataValueField = "SubjectID";             ddlSubject.DataBind();         }         catch (Exception ex)         {             // Handle the error         }      }      // Add the initial item - you can add this even if the options from the     // db were not successfully loaded     ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));  } 

To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:

<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">     <asp:ListItem Text="<Select Subject>" Value="0" /> </asp:DropDownList> 

You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:

ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0")); 

from the code-behind, or you'll have two "" items.

like image 98
Tim Avatar answered Oct 13 '22 12:10

Tim


I hope I am not overstating the obvious, but why not do it directly in the ASP side? Unless you are dynamically altering the SQL based on certain conditions in your program, you should avoid codebehind as much as possible.

You could do the above all in ASP directly without code using the SqlDataSource control and a property in your dropdownlist.

<asp:GridView ID="gvSubjects" runat="server" DataKeyNames="SubjectID" OnRowDataBound="GridView_RowDataBound" OnDataBound="GridView_DataBound">     <Columns>         <asp:TemplateField HeaderText="Subjects">             <ItemTemplate>                 <asp:DropDownList ID="ddlSubjects" runat="server" DataSourceID="sdsSubjects" DataTextField="SubjectName" DataValueField="SubjectID">                 </asp:DropDownList>                 <asp:SqlDataSource ID="sdsSubjects" runat="server"                     SelectCommand="SELECT SubjectID,SubjectName FROM Students.dbo.Subjects"></asp:SqlDataSource>             </ItemTemplate>         </asp:TemplateField>     </Columns> </asp:GridView> 
like image 36
Fandango68 Avatar answered Oct 13 '22 12:10

Fandango68