Saturday, March 31, 2018

WPF CRUD with DataGrid and Entity Framework (VB.NET)

Good morning!

Here's the VB.NET version of this post WPF CRUD with DataGrid and Entity Framework C#. The steps to accomplish basing from the C# post are:
a. Run the create table script assuming that you haven't created the Students table.
b. Create a VB.NET WPF project.
c. Replace the XAML markup of the window control.
Once done, the scripts for the repository class and window code-behind are as follows:
Repository Class
Public Class StudentRepository

    Private studentContext As StudentEntities = Nothing

    Public Sub New()
        studentContext = New StudentEntities()
    End Sub

    Public Function GetStudent(ByVal id As Integer) As Student
        Return studentContext.Students.Find(id)
    End Function

    Public Function GetAll() As List(Of Student)
        Return studentContext.Students.ToList()
    End Function

    Public Sub AddStudent(ByVal student As Student)
        If student IsNot Nothing Then
            studentContext.Students.Add(student)
            studentContext.SaveChanges()
        End If
    End Sub

    Public Sub UpdateStudent(ByVal student As Student)
        Dim studentFind = Me.GetStudent(student.ID)
        If studentFind IsNot Nothing Then
            studentFind.Name = student.Name
            studentFind.Contact = student.Contact
            studentFind.Age = student.Age
            studentFind.Address = student.Address
            studentContext.SaveChanges()
        End If
    End Sub

    Public Sub RemoveStudent(ByVal id As Integer)
        Dim studObj = studentContext.Students.Find(id)
        If studObj IsNot Nothing Then
            studentContext.Students.Remove(studObj)
            studentContext.SaveChanges()
        End If
    End Sub

End Class
Code Behind
Class MainWindow

    Private studentRepository As StudentRepository

    Private Property Id As Integer

    Public Sub New 
        ' This call is required by the designer.
        InitializeComponent()
        studentRepository  = New StudentRepository()
    End Sub

    Private Sub MainWindow_OnLoaded(sender As Object, e As RoutedEventArgs)
        Id = -1
        PopulateGrid()

    End Sub

    Private Sub PopulateGrid()
        DataGridStudents.ItemsSource = studentRepository.GetAll()
    End Sub
    
    Private Sub ButtonCancel_Click(sender As Object, e As RoutedEventArgs)
        ResetControls()
    End Sub

    Private Sub ResetControls()
        Me.Id = -1
        TextBoxName.Text = String.Empty
        TextBoxAge.Text = String.Empty
        TextBoxAddress.Text = String.Empty
        TextBoxContact.Text = String.Empty
    End Sub

    Private Sub ButtonEdit_OnClick(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim student = TryCast((CType(sender, FrameworkElement)).DataContext, Student)
        If student IsNot Nothing Then
            TextBoxName.Text = student.Name
            TextBoxAge.Text = student.Age.ToString()
            TextBoxAddress.Text = student.Address
            TextBoxContact.Text = student.Contact
            Me.Id = student.ID
        End If
    End Sub

    Private Sub ButtonSave_OnClick(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If Not String.IsNullOrEmpty(TextBoxAddress.Text) AndAlso Not String.IsNullOrEmpty(TextBoxAge.Text) AndAlso Not String.IsNullOrEmpty(TextBoxContact.Text) AndAlso Not String.IsNullOrEmpty(TextBoxName.Text) Then
            Try
                Dim student As Student = New Student() With {.Address = TextBoxAddress.Text, .Age = Convert.ToInt32(TextBoxAge.Text), .Contact = TextBoxContact.Text, .Name = TextBoxName.Text}
                If Me.Id <= 0 Then
                    studentRepository.AddStudent(student)
                    MessageBox.Show("New record successfully saved.")
                Else
                    student.ID = Me.Id
                    studentRepository.UpdateStudent(student)
                    MessageBox.Show("Record successfully updated.")
                End If
            Catch ex As Exception
                MessageBox.Show("An error occured unable to save record!", "", MessageBoxButton.OK, MessageBoxImage.Error)
                Debug.Print(ex.Message)
            Finally
                ResetControls()
                PopulateGrid()
            End Try
        End If
    End Sub

    Private Sub ButtonDelete_OnClick(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If MessageBox.Show("Confirm delete of this record?", "Student", MessageBoxButton.YesNo) = MessageBoxResult.Yes Then
            Dim student = TryCast((CType(sender, FrameworkElement)).DataContext, Student)
            If student IsNot Nothing Then
                Try
                    studentRepository.RemoveStudent(student.ID)
                    MessageBox.Show("Record successfully deleted")
                Catch ex As Exception
                    MessageBox.Show("An error occured. Unable to delete record!", "", MessageBoxButton.OK, MessageBoxImage.Error)
                Finally
                    ResetControls()
                    PopulateGrid()
                End Try
            End If
        End If
    End Sub

End Class
Output

0 comments:

Post a Comment