In this article I will explain with an example, how to select the data from database with
Stored Procedure using
Dapper library in Windows Forms (WinForms) Application using C# and VB.Net.
Installing Dapper package using Nuget
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Stored Procedure
CREATE PROCEDURE [Customers_GetCustomers]
AS
BEGIN
SET NOCOUNT ON;
SELECT [CustomerId]
,[Name]
,[Country]
FROM [Customers]
END
Form Design
The following form consists of:
DataGridView – For displaying data.
Namespaces
You will need to import the following namespaces.
C#
using Dapper;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports Dapper
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Selecting with Stored Procedure using Dapper in Windows Forms
Inside the Form Load event handler, first the connection is read from App.Config file.
The records are fetched from the
Customers Table of
SQL Server database with
Stored Procedure using
ExecuteReader method of
Dapper class and copied to
DataTable object using
Load method.
Finally, DataTable is assigned to the DataSource property of DataGridView.
C#
private void Form1_Load(object sender, EventArgs e)
{
string spName = "Customers_GetCustomers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (IDataReader sdr = con.ExecuteReader(spName, commandType: CommandType.StoredProcedure))
{
using (DataTable dtCustomers = new DataTable())
{
dtCustomers.Load(sdr);
dgvCustomers.DataSource = dtCustomers;
}
}
}
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim spName As String = "Customers_GetCustomers"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using sdr As IDataReader = con.ExecuteReader(spName, commandType:=CommandType.StoredProcedure)
Using dtCustomers As DataTable = New DataTable()
dtCustomers.Load(sdr)
dgvCustomers.DataSource = dtCustomers
End Using
End Using
End Using
End Sub
Screenshot
Downloads