Kayla Ninh Kayla Ninh - 1 month ago 15x
C# Question

Add ComboBox to WPF DataGrid that pulls from a SQL DataTable

I have a WPF program that allows users to edit an SQL data table for part details given a part number. The user enters a part number and I use a table adapter to display their part number details to a data grid using a row filter. I want to be able to take a list of ObservableCollection and bind it to a certain column in my data grid (i.e have a select list drop down list of part types for the part type column). Here is my .cs:

public MainWindow()
context = new RefreshAppContext();
PartTypeComboBox.ItemsSource = partTypesList;

public void findButton_Click(object sender, RoutedEventArgs e)
var partNumber = inputBox.Text;
// Searches for part number in db.
var foundPart = context.RefreshPartTypes.Where(x => x.PartNumber == partNumber).ToList();
if (!foundPart.Any() == true)
MessageBox.Show("Part not found. Please try another number.");
// Adapter used to fill DT with info from DB based on query(ies).
DataView dv = table_PT.DefaultView;
dv.RowFilter = "PartNumber='" + partNumber + "'";

// Fills data grid in UI.
dg.DataContext = dv;
PartTypeComboBox.ItemsSource = table_LV.DefaultView;
public void createDropDowns()
// Populate part styles from lookup table.
partTypesList = new ObservableCollection<string>();
List<string> temp = table_LV.AsEnumerable().Select(x => x[2].ToString()).ToList();
foreach (var partType in temp)
partTypesList.Add(""); // Add a blank option in case user needs to input blank cell.

And here is my .xaml:

<DataGrid x:Name="dg" ItemsSource="{Binding}" AutoGenerateColumns="True" AutoGeneratingColumn="m_grid_AutoGeneratingColumn" HorizontalAlignment="Left" Margin="28,-145,-779,0" VerticalAlignment="Top" Height="165" Width="1222" AlternatingRowBackground="LightGray" AlternationCount="2">
<DataGridComboBoxColumn x:Name="PartTypeComboBox"
SelectedValueBinding="{Binding PartType}"/>

I can get it to create a new ComboBox column with the correct list of information, but I cannot get that combobox to display (or bind?) onto my PartType Column populated from my table_PT data table. Direction? Thanks!



<DataGrid x:Name="dg" ItemsSource="{Binding}" AutoGenerateColumns="True" AutoGeneratingColumn="event_AutoGeneratingColumn" HorizontalAlignment="Left" Margin="28,-145,-134,0" VerticalAlignment="Top" Height="165" Width="582" AlternatingRowBackground="LightGray" AlternationCount="2">
                <DataGridTemplateColumn x:Name="comboCol" Header="PartTypeTest" Width="150">
                            <ComboBox ItemsSource="{Binding partTypesList, RelativeSource={RelativeSource AncestorType=Window}}" 
                                      SelectedItem="{Binding PartType, UpdateSourceTrigger=PropertyChanged}"/>