Nathan Nathan - 4 years ago 121
SQL Question

Prevent duplicate results in SQL

I have a combo box (

comboBox1
) in my application that lists catagories from my SQL database. It is pulling the data correctly at the moment. My only problem is that when the data is listed in the combo box, there are duplicate results. For example:

What I want it to list:

Example 1
Example 2
Example 3


What it actualy lists:

Example 1
Example 1
Example 1
Example 1
Example 1
Example 2
Example 2
Example 2
Example 3
Example 3
Example 3


Here is the code that I am using to list the data:

public void ListCat()
{
DataTable linkcat = new DataTable("linkcat");
using (SqlConnection sqlConn = new SqlConnection(@"Connection stuff;"))
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT name FROM list WHERE name <> 'NULL'", sqlConn))
{
da.Fill(linkcat);
}
}
foreach (DataRow da in linkcat.Rows)
{
comboBox1.Items.Add(da[0].ToString());
}
}


In short, my question would be how can I prevent duplicate data from being listed?

Answer Source

Use DISTINCT . It will eliminate the duplicate records.

Change your query to

SELECT DISTINCT name FROM list WHERE name <> 'NULL'

Assuming you may have stored the string value NULL inside your name column for some records.

If you have the real NULL in the name field, your query should be like this

SELECT DISTINCT name FROM list WHERE name is not NULL
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download