Windows Forms: Retrieve data from SQL database using Dapper in C#

Retrieve data from sql database using Dapper ORM, Stored Procedure in C# Windows Forms

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "Dapper1" and then click OK

dapper ormStep 2: Right click on your project select Manage NuGet Packages -> Search dapper -> Install

install dapper ormStep 3: Design your form as below

c# dapper

Step 3: Create a Category, Product class to map data return from sql database

public class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
}

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public decimal UnitPrice { get; set; }
    public int UnitsInStock { get; set; }
    public string QuantityPerUnit { get; set; }
}

Step 4: Add a connection string to the app.config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="cn" connectionString="Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=123@qaz;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>

Step 5: Create a DataService class to retrieve data from sql server

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;

namespace Dapper1
{
    public static class DataService
    {
        public static List<Category> GetAllCategory()
        {
            using(IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
            {
                if (db.State == ConnectionState.Closed)
                    db.Open();
                //Execute sql query
                return db.Query<Category>("select CategoryID, CategoryName from Categories").ToList();
            }
        }

        public static List<Product> GetProductByCategoryID(int categoryId)
        {
            using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
            {
                if (db.State == ConnectionState.Closed)
                    db.Open();
                //Execute stored procedure
                return db.Query<Product>("GetProductByCategoryId", new { CategoryID = categoryId }, commandType:CommandType.StoredProcedure).ToList();
            }
        }
    }
}

You can create a GetProductByCategoryId stored as below

CREATE procedure [dbo].[GetProductByCategoryId]
(
	@CategoryId int
)
as
	select *from Products where CategoryID = @CategoryId

Step 6: Add code to handle your winform as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Dapper1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Init data
            cboCategory.DataSource = DataService.GetAllCategory();
            cboCategory.DisplayMember = "CategoryName";
            cboCategory.ValueMember = "CategoryID";
            Category obj = cboCategory.SelectedItem as Category;
            if (obj != null)
                dataGridView.DataSource = DataService.GetProductByCategoryID(obj.CategoryID);
        }

        private void cboCategory_SelectionChangeCommitted(object sender, EventArgs e)
        {
            //Get product by category id
            Category obj = cboCategory.SelectedItem as Category;
            if (obj != null)
                dataGridView.DataSource = DataService.GetProductByCategoryID(obj.CategoryID);
        }
    }
}

VIDEO TUTORIALS