In this article I will explain with an example, how to update data into database 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.
Form Design
The following Form consists of:
Label – For labelling the controls.
TextBox – For capturing the values of CustomerId, Name and Country.
Button – For updating records.
Namespaces
You will need to import the following namespaces.
C#
using Dapper;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports Dapper
Imports System.Data.SqlClient
Imports System.Configuration
Updating the record using Dapper in Windows Forms
When Update button is clicked, first the connection string is fetched from App.Config file.
Then, using the
Execute method of
Dapper library record is updated into the
SQL Server database.
Finally, based on whether record is updated or not, an appropriate message is displayed using MessageBox class.
C#
private void OnUpdate(object sender, EventArgs e)
{
string sql = "UPDATE Customers SET Name=@Name, Country=@Country WHERE CustomerId=@CustomerId";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
int customerId = int.Parse(txtId.Text);
string name = txtName.Text;
string country = txtCountry.Text;
int i = con.Execute(sql, new { customerId, name, country });
if (i > 0)
{
MessageBox.Show("Customer record updated.");
}
else
{
MessageBox.Show("Customer not found.");
}
txtId.Text = string.Empty;
txtName.Text = string.Empty;
txtCountry.Text = string.Empty;
}
}
VB.Net
Private Sub OnUpdate(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim sql As String = "UPDATE Customers SET Name=@Name, Country=@Country WHERE CustomerId=@CustomerId"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Dim customerId As Integer = Integer.Parse(txtId.Text)
Dim name As String = txtName.Text
Dim country As String = txtCountry.Text
Dim i As Integer = con.Execute(sql, New With { customerId, name, country })
If i > 0 Then
MessageBox.Show("Customer record updated.")
Else
MessageBox.Show("Customer not found.")
End If
txtId.Text = String.Empty
txtName.Text = String.Empty
txtCountry.Text = String.Empty
End Using
End Sub
Screenshot
Downloads