Donate

WPF CRUD With DataGrid, Entity Framework And C#.NET

Good evening!

Here's a simple WPF CRUD(Create/Update/Delete) application using DataGrid and Entity Framework. This doesn't involve the MVVM pattern and input validation. Maybe if I have time, in the future I'll post an MVVM equivalent post (Update: I already have additional examples using RepoDB ORM and MVVM pattern in both C# and VB.NET at the end of this article). So to proceed, execute the SQL script below and make sure to replace the database name with an existing one.
USE [your_database]
GO

/****** Object:  Table [dbo].[Students]    Script Date: 3/31/2018 11:24:23 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Students](
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [Name] [varchar](50) NULL,
 [Age] [int] NULL,
 [Address] [varchar](50) NULL,
 [Contact] [varchar](50) NULL,
 CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED 
(
 [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO
Next is create a WPF project and then add an ADO.NET Entity Data Model that connects to the Students table in your database. Once done, add a repository class such as below that performs the CRUD operations.
public class StudentRepository
{
 private StudentEntities studentContext = null;

 public StudentRepository()
 {
  studentContext = new StudentEntities();
 }

 public Student Get(int id)
 {
  return studentContext.Students.Find(id);
 }

 public List<Student> GetAll()
 {
  return studentContext.Students.ToList();
 }

 public void AddStudent(Student student)
 {
  if (student != null)
  {
   studentContext.Students.Add(student);
   studentContext.SaveChanges();
  }
 }

 public void UpdateStudent(Student student)
 {
  var studentFind = this.Get(student.ID);
  if (studentFind != null)
  {
   studentFind.Name = student.Name;
   studentFind.Contact = student.Contact;
   studentFind.Age = student.Age;
   studentFind.Address = student.Address;
   studentContext.SaveChanges();
  }
 }

 public void RemoveStudent(int id)
 {
  var studObj = studentContext.Students.Find(id);
  if (studObj != null)
  {
   studentContext.Students.Remove(studObj);
   studentContext.SaveChanges();
  }
 }
}
In your XAML page, add the markup that includes DataGrid, TextBox and Button controls. These controls are contained in a StackPanel container.
<StackPanel Orientation="Vertical">
        <GroupBox Header="Student Form" Margin="10">
            <Grid Height="150">
                <Grid.RowDefinitions>
                    <RowDefinition Height="1*"/>
                    <RowDefinition Height="1*"/>
                    <RowDefinition Height="1*"/>
                    <RowDefinition Height="1*"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label Content="Name" HorizontalAlignment="Left" 
                       VerticalContentAlignment="Center" Grid.Column="0" Grid.Row="0"/>
                <TextBox Grid.Row="0" Grid.Column="1" x:Name="TextBoxName" Height="27" 
                       Margin="5"  Width="300" HorizontalAlignment="Left"/>
                <Label Content="Age" HorizontalAlignment="Left" VerticalContentAlignment="Center" 
                       Grid.Row="1" Grid.Column="0"/>
                <TextBox Grid.Row="1" Grid.Column="1" x:Name="TextBoxAge" Height="27" 
                       Margin="5" Width="70" HorizontalAlignment="Left"/>
                <Label Content="Address" HorizontalAlignment="Left" VerticalContentAlignment="Center" 
                       Grid.Row="2" Grid.Column="0" />
                <TextBox Grid.Row="2" Grid.Column="1" x:Name="TextBoxAddress" Height="27" 
                       Margin="5" Width="300" HorizontalAlignment="Left"/>
                <Label Content="Contact" HorizontalAlignment="Left" VerticalContentAlignment="Center" 
                       Grid.Row="3" Grid.Column="0" />
                <TextBox Grid.Row="3" Grid.Column="1" x:Name="TextBoxContact" Height="27"
                       Margin="5" Width="300" HorizontalAlignment="Left"/>
            </Grid>
        </GroupBox>
        <StackPanel Height="40" Orientation="Horizontal" HorizontalAlignment="Right">
            <Button x:Name="ButtonSave" Content="Save" Height="30" Width="80" Click="ButtonSave_OnClick"/>
            <Button x:Name="ButtonCancel" Content="Cancel" Height="30" Width="80" Margin="5,0,10,0" Click="ButtonCancel_Click"/>
        </StackPanel>
        <StackPanel Height="210">
            <DataGrid x:Name="DataGridStudents" AutoGenerateColumns="False"
                      CanUserAddRows="False" Height="200" Margin="10">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Binding="{Binding Path=ID}" Visibility="Hidden"/>
                    <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" Width="100"  IsReadOnly="True"/>
                    <DataGridTextColumn Header="Age" Binding="{Binding Path=Age}" Width="50"  IsReadOnly="True"/>
                    <DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" Width="180" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Contact" Binding="{Binding Path=Contact}" Width="125" IsReadOnly="True"/>
                    <DataGridTemplateColumn Width="50">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button Content="Select" x:Name="ButtonEdit" 
                                        Click="ButtonEdit_OnClick"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    <DataGridTemplateColumn Width="50">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button Content="Delete" x:Name="ButtonDelete"
                                        Click="ButtonDelete_OnClick"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>
        </StackPanel>
    </StackPanel>
In window's code behind, add the codes for the button events and other functionalities.
public partial class MainWindow : Window
    {
        private StudentRepository studentRepository;

        private int Id
        {
            get;
            set;
        }

        public MainWindow()
        {
            InitializeComponent();
            studentRepository = new StudentRepository();
        }

        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            Id = -1;
            PopulateGrid();
        }

        private void PopulateGrid()
        {
            DataGridStudents.ItemsSource = studentRepository.GetAll();
        }

        private void ButtonEdit_OnClick(object sender, RoutedEventArgs e)
        {
            var student = ((FrameworkElement) sender).DataContext as Student;
            if (student != null)
            {
                TextBoxName.Text = student.Name;
                TextBoxAge.Text = student.Age.ToString();
                TextBoxAddress.Text = student.Address;
                TextBoxContact.Text = student.Contact;
                this.Id = student.ID;
            }
        }

        private void ButtonCancel_Click(object sender, RoutedEventArgs e)
        {
            ResetControls();
        }

        private void ResetControls()
        {
            this.Id = -1;
            TextBoxName.Text = string.Empty;
            TextBoxAge.Text = string.Empty;
            TextBoxAddress.Text = string.Empty;
            TextBoxContact.Text = string.Empty;
        }

        private void ButtonSave_OnClick(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(TextBoxAddress.Text) && !string.IsNullOrEmpty(TextBoxAge.Text)
                && !string.IsNullOrEmpty(TextBoxContact.Text) && !string.IsNullOrEmpty(TextBoxName.Text))
            {
                try
                {
                    Student student = new Student()
                    {
                        Address = TextBoxAddress.Text,
                        Age = Convert.ToInt32(TextBoxAge.Text),
                        Contact = TextBoxContact.Text,
                        Name = TextBoxName.Text
                    };

                    if (this.Id <= 0) //save
                    {
                        studentRepository.AddStudent(student);
                        MessageBox.Show("New record successfully saved.");
                    }
                    else //save
                    {
                        student.ID = this.Id;
                        studentRepository.UpdateStudent(student);
                        MessageBox.Show("Record successfully updated.");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("An error occured unable to save record!", "",MessageBoxButton.OK,
                        MessageBoxImage.Error);
                    Debug.Print(ex.Message);
                }
                finally
                {
                    ResetControls();
                    PopulateGrid();
                }
            }
        }

        private void ButtonDelete_OnClick(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Confirm delete of this record?", "Student",MessageBoxButton.YesNo)
                == MessageBoxResult.Yes)
            {
                var student = ((FrameworkElement)sender).DataContext as Student;
                if (student != null)
                {
                    try
                    {
                        studentRepository.RemoveStudent(student.ID);
                        MessageBox.Show("Record successfully deleted");
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("An error occured. Unable to delete record!", "", MessageBoxButton.OK,
                            MessageBoxImage.Error);
                    }
                    finally
                    {
                        ResetControls();
                        PopulateGrid();
                    }
                }
            }
        }
    }
Output
WPF CRUD With DataGrid, Entity Framework And C#.NET

MVVM versions using C# and VB.NET
WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET
WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And VB.NET
RepoDB ORM in C#
WPF CRUD With DataGrid, RepoDB ORM And C#.NET

Comments

  1. Thank You for this APP.
    I'm a beginner of using VS 2019 and I'm missing the CodeFirst class of "Student.cs" and "studentContext",which heritates from "StudentEntities".
    I've problems with missing the namespace in "StudentResposity class". I get a debugging failure "CS0246" The type or namespace name "StudentEntities" and "Student" could not be found (are you missing a using directive or an assembly reference?). Where and how must I complete the code?

    Thank You waiting for Your answer.

    Philipp Eitner


    It shows in very understandable and simply kind the creation of a Database Application with the new experience of WPF Databinding integrated in Entity Framework 6 with new Model CodeFirst.


    Leider wird nicht auf den Entstehungsprozess (Migration) eines CodeFirst – Models „students.cs“ und „studentContext.cs“ eingegangen.
    Es fehlt der „studentContext“, der von estudentEntitiesrbt.

    ReplyDelete
  2. Hi, this concept applies the Database Approach First and not Code First.

    ReplyDelete
  3. Can you pls explain this “ var student = ((FrameworkElement) sender).DataContext as Student; “

    ReplyDelete
    Replies
    1. That is to get the DataContext of the row to which the sender (button) belongs to and then cast it to a Student object.

      Delete

Post a Comment

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Reference A Converter Class In A Resource Dictionary In WPF

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.