Click here to Skip to main content
15,894,646 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to bind certain fields to combo boxes and textboxes. As of now, I am having an issue using Select distinct from statement with creating a binding source using the data table created to fill the data source. I get the data, but not distinct values. I get all values including any duplicate type data.

Dim sqlconn2 As New SqlConnection("sqlstring")
     Dim da2 As New SqlDataAdapter("select distinct Id, county, [business name], [business license number], [business address] from businesses", sqlconn2)
     sqlconn2.Open()
     da2.SelectCommand.ExecuteNonQuery()
     Dim newdts As New DataTable
     da2.Fill(newdts)
     sqlconn2.Close()
     bs2.DataSource = newdts

     businessnamecombobox.DataSource = bs2
     businessnamecombobox.DisplayMember = "business name"
     businessnamecombobox.ValueMember = "business name"


What I have tried:

I have tried to use a filter with the bindingsource. bs2.filter, but it still isn't giving distinct values. Any suggestions?
Posted
Updated 3-Oct-17 18:56pm

1 solution

The distinct keyword applies to the whole set of columns you are selecting from a table. In your case if there are companies with the same business names in different counties then they will be selected as well.

In your combobox you do not see counties or other related information therefore it seems that it is duplicated.

You can either omit all other column from the select statement and retrieve only busines name from you table:

VB
Dim da2 As New SqlDataAdapter("select distinct [business name] from businesses", sqlconn2)


Or, add display additional details, such as county, license number, etc in your combobox

If you still want to display additional details but list the business name once you can use a window function:

select Id, county, [business name], [business license number], [business address] from 
(select Id, county, [business name], [business license number], [business address],
 row_number() OVER (partition by [business name] order by Id) rn
 from  businesses) a where rn = 1
 
Share this answer
 
v2
Comments
Member 11856456 4-Oct-17 1:49am    
What about combining to the bindingsource. Lets say I make multiple statements to make distinct columns, can I take those 4-5 sql statements and put them into 1 bindingsource?
chaau 11-Oct-17 21:24pm    
yes, you can. You can use a window function for this. See my improved solution
Karthik_Mahalingam 4-Oct-17 2:02am    
5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900