I’m new to LINQ and am trying to bind a Linq to SQL table to several controls (treeview, textbox, etc). I want to be able to make changes to textbox fields and save those updates back to the database easily.
I’m able to get the data from the database using:
Private LinqDB As New DataContext(My.Settings.dbConnection)
Property tblManufacturers As Table(Of dbManufacturers) _
= LinqDB.GetTable(Of dbManufacturers)()
And binding the stuff to the controls was pretty simple. The TreeView fills with all the ManufacturerNames, and when I click on one it fills the TextBoxes for editing.
The problem is that the results aren’t in the order I want in the treeview.
I was hoping something like:
Property tblManufacturers As Table(Of dbManufacturers) _
= LinqDB.GetTable(Of dbManufacturers)().OrderBy("ManufacturerName")
would work, but alas no.
I know I can use something like
Dim ManufacturerQuery = From ManufacturerName In tblManufacturers Order By ManufacturerName
But pushing changes back to the database seems more difficult.
EDIT: So, apparently I need to stop being cowardly and just try stuff…
Namespace Controls
Public Class ManufacturerWarranty
Private LinqDB As New DataContext(My.Settings.dbConnection)
Property tblManufacturers As Table(Of dbManufacturers) = LinqDB.GetTable(Of dbManufacturers)()
Property ManufacturerQuery = From m In tblManufacturers Order By m.ManufacturerName
Public Sub New()
InitializeComponent()
End Sub
Private Sub ManufacturerWarranty_Loaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Loaded
Me.DataContext = Me
End Sub
Private Sub TreeView1_MouseDoubleClick(sender As System.Object, e As System.Windows.Input.MouseButtonEventArgs) Handles TreeView1.MouseDoubleClick
StackPanel1.DataContext = e.OriginalSource.DataContext
End Sub
Private Sub cmdSave_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles cmdSave.Click
LinqDB.SubmitChanges()
End Sub
End Class
End Namespace
And then I just bind my TreeView to ManufacturerQuery instead of tblManufacturers. My Save button still works for submitting changes, even when they are made to ManufacturerQuery instead of tblManufacturers.
Ok, perhaps you want
So, to commit you’d do
What I wouldn’t do is keep the context open while the user is interacting with the GUI. Likewise I (probably) wouldn’t order the data unless I was displaying it to the user.