Tech Junkie Blog - Real World Tutorials, Happy Coding!: ASP.NET DropDownList Part 4: Bind DropDownList To A List Of Objects

Monday, July 21, 2014

ASP.NET DropDownList Part 4: Bind DropDownList To A List Of Objects

In this part of the tutorial we will bind a DropDownList control to a list of objects.  This common practice if you are working with business objects that are mapped to the database table.  We will create a business object call "Category" and create a list call "categories" in our .aspx page.


One of the most commonly used server controls in ASP.NET is the DropDownList control.  In this blog I will show you how to bind a list of objects to a DropDownList control.

1. Create a .aspx page
2. Click on the "Toolbox" panel




3.  Drag the DropDownList control into a design surface


4. Create a connection string in the Web.Config file
  <connectionStrings>
    <add name="NorthwindConnectionString" connectionString="Data Source=(local);
Initial Catalog=Northwind;Integrated Security=True" 
providerName="System.Data.SqlClient"/>
  </connectionStrings>

5. Create a new folder in your project call "BusinessObjects" then add a .cs file call "Category.cs"

6. In the "Category.cs" file type in the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BusinessObjects
{
    public class Category
    {
        private int _categoryID;
        private string _categoryName;

        public Category(int Id, string Name)
        {
            this._categoryID = Id;
            this._categoryName = Name;
        }


        public int CategoryID
        {
            get { return this._categoryID; }
            set { this._categoryID = value; }
        }

        public string CategoryName
        {
            get { return this._categoryName; }
            set { this._categoryName = value; }
        }

    }
}   

7.  In the code behind page(.cs) page of the .aspx page, type in the following lines at the top to use the following libraries
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Data;
using BusinessObjects;
8. Create a new method call BindCategoriesListObjects() that returns void
        
protected void BindCategoriesListObjects()
{
     DataTable dtCategories = new DataTable();
     string connectString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].
ConnectionString;
     List categories = new List();

     using (SqlConnection conn = new SqlConnection(connectString))
     {
        SqlCommand cmd = new SqlCommand("SELECT CategoryID,CategoryName FROM Categories", conn);
        conn.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        adapter.Fill(dtCategories);


       foreach (DataRow row in dtCategories.Rows)
       {
           categories.Add(new Category(Convert.ToInt32(row["CategoryID"].ToString()),
           row["CategoryName"].ToString()));
       }
                
       //used to set the DropDownList1.DataSource to categories list of objects
       DropDownList1.DataSource = categories;

       DropDownList1.DataTextField = "CategoryName";

       DropDownList1.DataValueField = "CategoryID";
       DropDownList1.DataBind();

     }


}
The code above creates new DataTable call dtCategories, then it connects to the database using the "NorthwindConnectionString", and queries the CategoryID, and CategoryName in the Categories table in the Northwind database. The query results are then stored in the DataTable. Then we iterate through the DataTable dtCategories with the foreach loop and create a list of "Category" objects call "categories". The list "Category" objects is then bind to the DropDownList1 control.
                
       //used to set the DropDownList1.DataSource to categories list of objects
       DropDownList1.DataSource = categories;

       DropDownList1.DataTextField = "CategoryName";

       DropDownList1.DataValueField = "CategoryID";
       DropDownList1.DataBind();

9. Call the BindCategoriesListObjects() method in the Page_Load method
        protected void Page_Load(object sender, EventArgs e)
        {
             BindCategoriesListObjects();
            
        }
10. Run the application and you will see the DropDownList1 control populated with the Category Names in the Northwind database










11. If you look at the HTML source code you will see the following
<select name="DropDownList1" id="DropDownList1">
 <option value="1">Beverages</option>
 <option value="2">Condiments</option>
 <option value="3">Confections</option>
 <option value="4">Dairy Products</option>
 <option value="5">Grains/Cereals</option>
 <option value="6">Meat/Poultry</option>
 <option value="7">Produce</option>
 <option value="8">Seafood</option>
</select>





Related Blogs:
  1. Bind a DataTable To A DropDownList
  2. (DropDownList) Setting Default Value on First Page Load
  3. Use The DropDownList Control To Populate GridView
  4. Bind DropDownList To A List Of Objects

21 comments:

  1. I like the helpful info you provide in the articles. I will bookmark

    Free Iphone 7 Government Phone

    ReplyDelete

Search This Blog