Windows Forms: Insert Update Delete and View data from SQL Database using NPoco ORM in C#

By FoxLearn 6/18/2017 10:46:08 AM   7.3K
How to Insert, Update, Delete and View Student Profile data from SQL database using NPoco ORM, Stored Procedure, Metro Framework in C#

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

crud-ado-net

Step 2: Right click on your project select Manage NuGet Packages -> Search metro framework, npoco -> Install

install metro framework

If you don't see the metro framework in your toolbox, you can view How to download and install metro framework

NPoco is a Micro-ORM, extremely easy to use, supporting Sql Server, MySQL, PostgreSQL, Oracle, Sqlite, SqlCE. Originally Schotime's PetaPoco branch

Step 3: Design metro form as below

insert update delete view data using sql database

Step 4: You should create a new database, then add a student table to your database

CREATE TABLE [dbo].[Students](
    [StudentID] [int] IDENTITY(1,1) NOT NULL,
    [FullName] [nvarchar](100) NULL,
    [Birthday] [varchar](10) NULL,
    [Gender] [bit] NULL,
    [Email] [varchar](100) NULL,
    [Address] [nvarchar](250) NULL,
    [ImageUrl] [varchar](250) NULL,
 CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED
(
    [StudentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Create a stored procedure to insert, update data to student table

create procedure [dbo].[sp_Students_Update]
(
    @StudentID int output,
    @FullName nvarchar(100),
    @Birthday varchar(10),
    @Gender bit,
    @Email varchar(100),
    @Address nvarchar(250),
    @ImageUrl varchar(250)
)
as
    update Students set FullName = @FullName, Birthday = @Birthday, Gender = @Gender, Email = @Email, [Address] = @Address, ImageUrl = @ImageUrl
    where StudentID = @StudentID
   
go
   
create procedure [dbo].[sp_Students_Insert]
(
    @StudentID int output,
    @FullName nvarchar(100),
    @Birthday varchar(10),
    @Gender bit,
    @Email varchar(100),
    @Address nvarchar(250),
    @ImageUrl varchar(250)
)
as
    insert into Students(FullName, Birthday, Gender, Email, [Address], ImageUrl)
    values(@FullName, @Birthday, @Gender, @Email, @Address, @ImageUrl)
    set @StudentID = SCOPE_IDENTITY()

Step 5: Create an EntityState to manage objects state

public enum EntityState
{
    Unchanged,
    Added,
    Changed,
    Deleted
}

Step 6: Add a connection string to the App.config file

<configuration>
  <connectionStrings>
    <add name = "cn" connectionString="Data Source=.;Initial Catalog=dbstudent;User ID=sa;Password=123@qaz;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>

Step 7: Add code to handle your form as below

using NPoco;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;

namespace CRUD
{
    public partial class Form1 : MetroFramework.Forms.MetroForm
    {
        //Set default object state
        EntityState objState = EntityState.Unchanged;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "JPEG|*.jpg|PNG|*.png", ValidateNames = true })
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    //Load image from file to picturebox control
                    pic.Image = Image.FromFile(ofd.FileName);
                    //Get current student, then set image url
                    Student obj = studentBindingSource.Current as Student;
                    if (obj != null)
                        obj.ImageUrl = ofd.FileName;
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                using(IDatabase db = new Database("cn"))
                {
                    //Get students, then add students to binding source
                    studentBindingSource.DataSource = db.Fetch<Student>();
                    Student obj = studentBindingSource.Current as Student;
                    if (obj != null)
                    {
                        if (!string.IsNullOrEmpty(obj.ImageUrl))
                            pic.Image = Image.FromFile(obj.ImageUrl);
                    }
                    pContainer.Enabled = false;
                }
            }
            catch(Exception ex)
            {
                MetroFramework.MetroMessageBox.Show(this, ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            objState = EntityState.Added;
            pic.Image = null;
            pContainer.Enabled = true;
            //Add new student to binding source
            studentBindingSource.Add(new Student());
            studentBindingSource.MoveLast();
            txtFullName.Focus();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            objState = EntityState.Changed;
            pContainer.Enabled = true;
            txtFullName.Focus();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            objState = EntityState.Deleted;
            if(MetroFramework.MetroMessageBox.Show(this,"Are you sure want to delete this record?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    Student obj = studentBindingSource.Current as Student;
                    if (obj != null)
                    {
                        using(IDatabase db = new Database("cn"))
                        {
                            //Execute query to delete data
                            db.Execute("delete from Students where StudentID = @StudentID", new { StudentID = obj.StudentID });
                            studentBindingSource.RemoveCurrent();
                            pContainer.Enabled = false;
                            pic.Image = null;
                            objState = EntityState.Unchanged;
                        }
                    }
                }
                catch(Exception ex)
                {
                    MetroFramework.MetroMessageBox.Show(this, ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            pContainer.Enabled = false;
            studentBindingSource.ResetBindings(true);
            this.Form1_Load(sender, e);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                studentBindingSource.EndEdit();
                Student obj = studentBindingSource.Current as Student;
                if (obj != null)
                {
                    using(IDatabase db = new Database("cn"))
                    {
                        if (objState == EntityState.Added)
                        {
                            //Execute store to insert data, then get output parameter
                            SqlParameter pId = new SqlParameter("@StudentID", SqlDbType.Int) { Direction = ParameterDirection.Output };
                            Sql result = Sql.Builder.Append("sp_Students_Insert @StudentID out, @FullName, @Birthday, @Gender, @Email, @Address, @ImageUrl", new {
                                StudentID = pId,
                                FullName = obj.FullName,
                                Birthday = obj.Birthday,
                                Gender = obj.Gender,
                                Email = obj.Email,
                                Address = obj.Address,
                                ImageUrl = obj.ImageUrl
                            });
                            db.Execute(result);
                            obj.StudentID = (int)pId.Value;
                        }
                        else if (objState == EntityState.Changed)
                        {
                            //Execute stored procedure to update database
                            db.Execute("sp_Students_Update", CommandType.StoredProcedure, new { StudentID = obj.StudentID, FullName = obj.FullName, Gender = obj.Gender, Email = obj.Email, Address = obj.Address, Birthday = obj.Birthday, ImageUrl = obj.ImageUrl });
                        }
                        metroGrid.Refresh();
                        pContainer.Enabled = false;
                        objState = EntityState.Unchanged;
                    }
                }
            }
            catch (Exception ex)
            {
                MetroFramework.MetroMessageBox.Show(this, ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void metroGrid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            Student obj = studentBindingSource.Current as Student;
            if (obj != null)
            {
                if (!string.IsNullOrEmpty(obj.ImageUrl))
                    pic.Image = Image.FromFile(obj.ImageUrl);
            }
        }
    }
}

VIDEO TUTORIALS