In my WPF project I am trying to bind a Combobox to a database table column and avoid duplicates. I'm using Entity Framework. So far I have been able to succeed binding the Combobox to the column(as EF do most of the work), but I can not get rid of the duplicates.
The thing is my database called Departments has 2 columns. One named DepartmentID and one named DepartmentName. The DepartmentName is the one I want and the one that has the duplicates(which is not a mistake in the setup). I also have a table called Employees with a foreign key reference to DepartmentID.
I have tried a few suggestions using LINQ and creating a list, but without any luck. I have tried using Filter with a collectionViewSource. I have tried with a converter. I have tried using Distinct in all sorts of ways, and lately I have tried grouping the DepartmentNames. None of it with success.
Here is what is currently showing the DepartmentNames but with a lot of duplicates.
Resources:
<CollectionViewSource x:Key="employeeViewSource" d:DesignSource="{d:DesignInstance {x:Type local:Employee}, CreateList=True}"/>
The combobox:
<ComboBox x:Name="departmentNameComboBox" DataContext="{StaticResource employeeViewSource}"
ItemsSource="{Binding}" DisplayMemberPath="Department.DepartmentName" HorizontalAlignment="Left" Height="Auto" Margin="3" VerticalAlignment="Center" Width="120"/>
All I really want, is for that damn ComboBox to show only different department names. I thought it would be easy, but having spend the whole day yesterday, it seems I isn't. At least not for me. :-) Can anyone help?
I suggest you just create a database object that only selects the columns that you actually need and bind your combobox to that. I find that to be the cleanest solution because you can just change the source table/view and the combobox will just adapt.