3

TwoWay binding a table to a datagrid which has a ComboBox column and bind to another table?

I have a datagrid which is twoway bind to table Accounts. Whenever the update button is clicked, I'll update the data adapter, which updates the table. It works fine.

Now, in the table Accounts, there is a column called LocationCode. The value of LocationCode comes from another table Locations. So, when the user makes changes to LocationCode in the datagrid, the user should be able to choose the LocationCode from a list of values in table Locations. It means in the datagrid, LocationCode column should be a ComboBox column whose DataContent is the table Locations.

Is there a way that in the datagrid, it shows the value of table Accounts, but when user click Locations cell, it will show a comboBox, so user can choose from the comboBox. Once the value is updated, If I update the data adapter, it will update the table Accounts automatically (twoway binding)?

Here is what I'm doing for now:

<DataGrid AutoGenerateColumns="false" Name="dgActLoc" Grid.Row="0" IsReadOnly="false" FontWeight="Bold" Padding="5" Margin="5" ItemsSource="{Binding Path=., Mode=TwoWay}" SelectionMode="Single" FontSize="16" RowDetailsVisibilityMode="VisibleWhenSelected" PreparingCellForEdit="dgActLoc_PreparingCellForEdit">

<DataGrid.Columns>

    <DataGridTextColumn Binding="{Binding Path=AcctLocID, Mode=TwoWay}" Header="Account Location ID" IsReadOnly="True" >

        blah, blah

    </DataGridTextColumn> 
    <DataGridTextColumn Binding="{Binding Path=AccountID, Mode=TwoWay}" Header="Account ID" />

        blah, blah

    <DataGridComboBoxColumn Header="Location Code" Width="*"  SelectedValueBinding="{Binding Path=LocationCode}" SelectedValuePath="LocationCode" DisplayMemberPath="LocationCode" >

    </DataGridComboBoxColumn>

</DataGrid>

Then in the code behind:

private void dgActLoc_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
{
    if (e.Column.Header.Equals("Location Code"))
    {
        string cmd = "SELECT LocationCode FROM Location ORDER BY LocationCode";
        DataTable dt = clsDataAccess.GetTableFromDB(cmd);

        ComboBox cboEditingElement = (ComboBox)(e.EditingElement);
        BindingOperations.SetBinding(cboEditingElement, ComboBox.ItemsSourceProperty, new Binding() { Source = dt });

    }
}

However, it has a problem. When the window shows up, the column is blank even it should have a value (red circle).

enter image description here

If I click the cell, the combobox shows up, and I can select the value. If I click Update button, it updates the value in table.

enter image description here

So, my question is: why it is blank (in the first screen shot), how to fix it?

thanks

urlreader
  • 6,319
  • 7
  • 57
  • 91

0 Answers0