WPF Insert into SQL Server Table with Dapper


This entry is part 3 of 5 in the series Dapper

In this post we look at inserting a row of data into a SQL Server table from a WPF project. The project is very simple and the front-end is not fully designed yet, but here we just want to make sure we have the code that will insert records based on some information that a user has entered into three TextBoxes.

The screenshot below shows the main window of the project. We have another window that the user uses to enter data and then click the Add button.

<Window x:Class="DapperPusherYouTube.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DapperPusherYouTube"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="DapperPusherYouTube" Height="250" Width="450">
    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <Button x:Name="BtnWin" Click="BtnWin_Click" Height="25" Width="120" Margin="12,0,0,0" >Add</Button>
            <Button x:Name="BtnRefresh" Click="BtnRefresh_Click" Height="25" Width="120" Margin="12,0,0,0">Refresh</Button>
        </StackPanel>
        <DataGrid x:Name="dtaGrid" HorizontalAlignment="Left" Height="170" 
                  Margin="20,10,0,0" VerticalAlignment="Top" Width="389"/>
    </StackPanel>
</Window>

using System.Data;
using System.Windows;
using System.Data.SqlClient;
using Dapper;
using System;

namespace DapperPusherYouTube
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            LoadTable();  // display table data in Grid with SQL SELECT statement 
        }
        IDbConnection GetConnection()
        {
            return new SqlConnection("Server=(localdb)\\MSSQLLocalDB;Database=MyApp1;Integrated Security=true;");
        }
        private void LoadTable()
        {
            try
            {
                using (IDbConnection conn = GetConnection())
                {
                    // IEnumerable<Customer>
                    var customer = conn.Query<Customer>("SELECT * FROM Customers");
                    dtaGrid.ItemsSource = customer;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Database Error: " + ex.Message, "DapperPusherYouTube",
                    MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        private void BtnWin_Click(object sender, RoutedEventArgs e)
        {
            var win2 = new Window1();
            win2.ShowDialog();
        }

        private void BtnRefresh_Click(object sender, RoutedEventArgs e)
        {
            LoadTable();
        }
    }
    public class Customer
    {
        public int CustomerId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
    }
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

<Window x:Class="DapperPusherYouTube.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DapperPusherYouTube"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="Window1" Height="250" Width="400">
    <StackPanel>

        <StackPanel HorizontalAlignment="Left" Orientation="Horizontal" Margin="10,10,0,0">
            <Label>First Name: </Label>
            <TextBox Name="txtBoxFirstName" Margin="16,0,0,0" TextWrapping="Wrap" Text="" Width="120"/>
        </StackPanel>
        <StackPanel HorizontalAlignment="Left" Orientation="Horizontal" Margin="10,10,0,0">
            <Label>Last Name:</Label>
            <TextBox Name="txtBoxLastName" Margin="16,0,0,0" TextWrapping="Wrap" Text="" Width="120"/>
        </StackPanel>
        <StackPanel HorizontalAlignment="Left" Orientation="Horizontal" Margin="10,10,0,0">
            <Label>Email:</Label>
            <TextBox Name="txtBoxEmail" Margin="16,0,0,0" TextWrapping="Wrap" Text="" Width="120"/>
        </StackPanel>
        <Button Name="btnAdd" Content="Add" HorizontalAlignment="Left" Margin="151,20,0,0" 
                VerticalAlignment="Top" Width="120" Height="30" Click="BtnAdd_Click"/>
    </StackPanel>
</Window>

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows;
using Dapper;
namespace DapperPusherYouTube
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
        private void BtnAdd_Click(object sender, RoutedEventArgs e)
        {
            try  // this is inside a click event
            {
                using (IDbConnection conn = GetConnection())
                {
                    string sql = "INSERT INTO Customers (FirstName, LastName, Email) VALUES (@FirstName, @LastName, @Email)";
                    conn.Execute(sql, new { FirstName = txtBoxFirstName.Text,
                                            LastName = txtBoxLastName.Text,
                                            Email = txtBoxEmail.Text});    // parameters 
                    MessageBox.Show("Added.", "Dapper");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Database Error: " + ex.Message, "DapperPusherYouTube",
                    MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        IDbConnection GetConnection()
        {
            return new SqlConnection("Server=(localdb)\\MSSQLLocalDB;Database=MyApp1;Integrated Security=true;");
        }
    }
}

After the user clicks the Add button the data is added to the database and the message box appearsas a confirmation. The Winsow1 (Add) windows does not automatically disappear so that the user may continue to add more records. The main intercae showing the list of records in the database is not automatically refreshed. The Refresh button will automatically load the data into the DataGrid and you will then see the updated records.

Series Navigation<< WPF Read a SQL Server Table into a DataGrid with DapperDapper Installation into your Project in Visual Studio >>