Creating a DataGrid using an SQL database and LINQ to SQL
Step 1:
Make sure the .dbml item has been added to the project and the database tables have
been dragged to the .dbml surface. It helps if the table's relationships have been
established. If tables, or relationships have been modified, the corresponding tables
in the .dbml need to be revised by simply deleting the modified table in the .dbml
surface and re-dragging the table to the .dbml surface.
Step 2:
Create the DataGrid in the WPF window. Create the columns and bind the columns to
the cooresponding fields in the database. The double click event is added so the
user can double click a row instead of having to click a button. These columns are
set to be read only so no modification is possible on the DataGrid as in this example,
it's only used as a way to select a row. Additionally, the StringFormat is used
to view the date field as a date and not date and time.
Example
<DataGrid
MouseDoubleClick="NameOfDataGrid_MouseDoubleClick"
AutoGenerateColumns="False"
Margin="213,150,12,70"
Name="NameOfDataGrid">
<DataGrid.Columns>
<DataGridTextColumn
IsReadOnly="True"
Header="fieldName1"
Binding="{Binding Path=fieldName1}"/>
<DataGridTextColumn
IsReadOnly="True"
Header="fieldNamedate"
Binding="{Binding Path=fieldNameDate, StringFormat={}{0:d}}" />
</DataGrid.Columns>
</DataGrid>
Step3:
The DataGrid will need to refresh during a few operations. If, say, a row is selected,
and a new window is made to revise the data for that row, the list will need to
show the new information. The code statements to build the list of information should
be put into its own method. Here is an example of the code snippet that will perform
the building of the list using a LING Query and creating a Database connection.
an example of ordering (orderby) and filtering (where) is included. The list would
generally be called in the Window_Loaded event.
private void buildListforDataGrid()
{
NameOfDataContext DatabaseConnection = new NameOfDataContext();
List<linqtablename> NameForTheList = (
from s in DatabaseConnection.LinqTableName
where s.UniqueID == UniqueIDNumber
orderby s.fieldNameDate
select s).ToList();
NameOfDataGrid.ItemsSource = NameForTheList;
}
The list would generally be called in the Window_Loaded event and after an instance
of a new dialog or window is
private void Window_Loaded(object sender, RoutedEventArgs e)
{
buildListforDataGrid();
}