Charindu Edirisuriya Charindu Edirisuriya - 4 months ago 9
SQL Question

ASP.NET DropDownList Duplicate Values from Database

My Database is Like This.

Vehicle Make | Vehicle Model
-----------------------------
Toyota | AQUA
HONDA | FIT
Toyota | Prius


DropDownList1
, Populates Like this.

using (SqlConnection con = new SqlConnection(constring))
{

SqlDataAdapter adapter = new SqlDataAdapter("SELECT VehicleMake FROM VehicleDB", con);
adapter.Fill(subjects);

con.Open();


DropDownList1.DataSource = subjects;
DropDownList1.DataTextField = "VehicleMake";
DropDownList1.DataValueField = "VehicleMake";
DropDownList1.DataBind();

con.Close();

}


But since i have duplicate data(2 Toyota's), it shows them in the DropDownList too.

Is it possible to filter and only have 1 Toyota?

-PS

I need it added my database, as there are may more Vehicle makes too add.

Answer

Sure, you can use DISTINCT:

SqlDataAdapter adapter = new SqlDataAdapter("SELECT DISTINCT VehicleMake FROM VehicleDB", con);

You might want to add an ORDER BY too:

string sql = @"SELECT DISTINCT VehicleMake 
               FROM VehicleDB
               ORDER BY VehicleMake ASC";
using(var  adapter = new SqlDataAdapter(sql, con))
{
    // ...
}
Comments