Introduction
This sample demonstrates how to bind a DataTable to a DataGrid, and how to present a details section for the selected item (selected row of the DataGrid). This shows two way DataTable binding and converter for extra fields.
Building the Sample
Just download, unzip, open and run!
Description
This sample is in response to a WPF furum question regarding DataTable binding in a Master/Detail scenario.
In our example code, the database layer is removed, generating the data manually. In practive this is just created with an SQLDataAdapter. Changes can then be saved with the adapter's Update method.
C#
Edit|Remove
csharp
void MakeDataTable()
{
MyDataTable = new DataTable();
MyDataTable.Columns.Add("Name", typeof(string));
MyDataTable.Columns.Add("Weight", typeof(int)); // Kg
MyDataTable.Columns.Add("Height", typeof(int)); // Metres
MyDataTable.Rows.Add("Peter", 89, 2);
MyDataTable.Rows.Add("Paul", 70, 1.5);
}
void MakeDataTable()
{
MyDataTable = new DataTable();
MyDataTable.Columns.Add("Name", typeof(string));
MyDataTable.Columns.Add("Weight", typeof(int));
MyDataTable.Columns.Add("Height", typeof(int));
MyDataTable.Rows.Add("Peter", 89, 2);
MyDataTable.Rows.Add("Paul", 70, 1.5);
}
The DefaultView of the DataTable is then bound to the ItemsSource of the DataGrid:
C#
Edit|Remove
csharp
dg1.ItemsSource = MyDataTable.DefaultView;
dg1.ItemsSource = MyDataTable.DefaultView;
At this point you have everything you need to list, edit and even add rows to the database.
In our scenario however, it is imagined there are other details to show, and maybe extra columns of data which isn;t represented in the DataGrid. In our example, the DataGrid AutoGenerateColumns is true, so we see all the rows. I have disabled UserCanAddRows
just as that is not part of this design.
XAML
Edit|Remove
xaml
<DataGrid x:Name="dg1" HorizontalAlignment="Center" VerticalAlignment="Center" CanUserAddRows="False" />
<DataGrid x:Name="dg1" HorizontalAlignment="Center" VerticalAlignment="Center" CanUserAddRows="False" />
Finally, the SelectedItem is used as DataContext for the details grid. Then all controls within can bind directly to the SelectedItem's properties.
XAML
Edit|Remove
xaml
<Grid Grid.Row="1" DataContext="{Binding SelectedItem, ElementName=dg1}" >
<Grid Grid.Row="1" DataContext="{Binding SelectedItem, ElementName=dg1}" >
Source Code Files
- MainWindow.xaml - Startup window
- DataTable creation and binding
- Converters.cs - BMI calculation for extra form field
