ARTICLE

DataGridView - Insert, Update, Delete and Retrieve records using stored procedure

Posted by Suthish Nair Articles | ASP.NET Controls in C# October 18, 2010
This article is about DataGridView control that shows some basics data operations like inserts, updates, deletes and retrieve records using stored procedure.
Reader Level:
Download Files:
 

Article is about DataGridView control that shows some basics data operations like inserts, updates, and deletes using stored procedure.

Introduction

DataGridView control is the most popular amongst Windows Forms developers. Control helps to display data in a tabular format. The DataGridView control allows viewing, inserting, updating, or deleting data in a db table. Here am trying to show a simple example, how to retrieve, add/update or delete records using DataGridView. 

Getting Started

Before getting started this sample uses Northwind database and Visual Studio 2008. 


Following namespaces used:

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

This sample does not using any table from Northwind, but created a simple table named (dbo.UserMaster). It's a simple User Master Table using for saving First Name, Last Name, City and Phone Number. Also, contains one identity column (SNo). Stored Procedure using [dbo].[UserDetailsSummary].

1.gif 
Now create a windows application project, drag and drop DataGridView control to Form window. Set true for "Enable Adding", "Enable Deleting" and "Enable Editing" from DataGridView designer. This will enable control for editing, adding, deleting records. Add a checkbox control into DataGridView which uses as a selection for deletion of records.

2.gif

The Code

Form contains three buttons: 

Retrieve, Add/Update (Enabled False) and Delete (Enabled False).

btnRetrieve_Click: Retrieving records from db table which uses stored procedure by passing input parameters (method used: AddParameteres) which check for records exists. If found returning all the rows from User Master Table or if not returning a dummy row. If more than one row found, buttons Add/Update and Delete property changing to Enabled True.

dgvUsers_DataBindingComplete: Once DataGridView data binding completes, this events call to set column (SNo) property readonly to true. This will helps to disable editing of identity column.

btnAddEdit_Click: Event used for adding or editing records by looping through the DataGridView control. SqlTransaction used for successful commit or rollback if any error occurs.

btnDelete_Click: Event used for deleting records depending upon checkbox selection of DataGridView control.

Summary

Code samples attached also with sql scripts. Test the code and post your comments. There will be different better ways of doing these DataGridView operations. If anyone interested in making an article, please come forward and share the knowledge.

Login to add your contents and source code to this article
Article Extensions
Contents added by Tue NgoTri on Apr 01, 2013
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
using HYPO.DBO.AO;
namespace HYPO.DBO.BO
{
    public partial class BillBO
    {
        static public long Insert(BillAO ao)
        {
            try
            {
                SqlParameter[] Params =
                {
                    new SqlParameter("@Status",ao.Status)
                    , new SqlParameter("@BAID",ao.BAID)
                    , new SqlParameter("@PhieuKhamID",ao.PhieuKhamID)
                    , new SqlParameter("@ThuNganID",ao.ThuNganID)
                    , new SqlParameter("@Ngay",ao.Ngay)
                    , new SqlParameter("@SoTien",ao.SoTien)
                    , new SqlParameter("@LyDo",ao.LyDo)
                    , new SqlParameter("@GhiChu",ao.GhiChu)
                    , new SqlParameter("@CreatedBy",ao.CreatedBy)
                    , new SqlParameter("@CreatedTime",ao.CreatedTime)
                    , new SqlParameter("@LastModifiedBy",ao.LastModifiedBy)
                    , new SqlParameter("@LastModifiedTime",ao.LastModifiedTime)
                };
                int result = int.Parse(SqlHelper.ExecuteScalar(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_Insert", Params).ToString());
                return result;
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("duplicate"))
                {
                    return -2;
                }
                return -1;
            }
        }
        static public BillAO SelectByID(long id)
        {
            BillAO ret = new BillAO();
            DataSet ds;
            try
            {
                SqlParameter[] Params =
                {
                    new SqlParameter("@ID",id)
                };
                ds = SqlHelper.ExecuteDataset(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_SelectByID", Params);
                ret.ID = (long) (ds.Tables[0].Rows[0]["ID"] == DBNull.Value ? default(long) : ds.Tables[0].Rows[0]["ID"]);
                ret.Status = (bool) (ds.Tables[0].Rows[0]["Status"] == DBNull.Value ? default(bool) : ds.Tables[0].Rows[0]["Status"]);
                ret.BAID = (long) (ds.Tables[0].Rows[0]["BAID"] == DBNull.Value ? default(long) : ds.Tables[0].Rows[0]["BAID"]);
                ret.BAIDBenhAn = (string) (ds.Tables[0].Rows[0]["BAIDBenhAn"] == DBNull.Value ? default(string) : ds.Tables[0].Rows[0]["BAIDBenhAn"]);
                ret.PhieuKhamID = (long) (ds.Tables[0].Rows[0]["PhieuKhamID"] == DBNull.Value ? default(long) : ds.Tables[0].Rows[0]["PhieuKhamID"]);
                ret.PhieuKhamIDPhieuKham = (string) (ds.Tables[0].Rows[0]["PhieuKhamIDPhieuKham"] == DBNull.Value ? default(string) : ds.Tables[0].Rows[0]["PhieuKhamIDPhieuKham"]);
                ret.ThuNganID = (int) (ds.Tables[0].Rows[0]["ThuNganID"] == DBNull.Value ? default(int) : ds.Tables[0].Rows[0]["ThuNganID"]);
                ret.Ngay = (DateTime) (ds.Tables[0].Rows[0]["Ngay"] == DBNull.Value ? default(DateTime) : ds.Tables[0].Rows[0]["Ngay"]);
                ret.SoTien = (decimal) (ds.Tables[0].Rows[0]["SoTien"] == DBNull.Value ? default(decimal) : ds.Tables[0].Rows[0]["SoTien"]);
                ret.LyDo = (string) (ds.Tables[0].Rows[0]["LyDo"] == DBNull.Value ? default(string) : ds.Tables[0].Rows[0]["LyDo"]);
                ret.GhiChu = (string) (ds.Tables[0].Rows[0]["GhiChu"] == DBNull.Value ? default(string) : ds.Tables[0].Rows[0]["GhiChu"]);
                ret.CreatedBy = (int) (ds.Tables[0].Rows[0]["CreatedBy"] == DBNull.Value ? default(int) : ds.Tables[0].Rows[0]["CreatedBy"]);
                ret.CreatedTime = (DateTime) (ds.Tables[0].Rows[0]["CreatedTime"] == DBNull.Value ? default(DateTime) : ds.Tables[0].Rows[0]["CreatedTime"]);
                ret.LastModifiedBy = (int) (ds.Tables[0].Rows[0]["LastModifiedBy"] == DBNull.Value ? default(int) : ds.Tables[0].Rows[0]["LastModifiedBy"]);
                ret.LastModifiedTime = (DateTime) (ds.Tables[0].Rows[0]["LastModifiedTime"] == DBNull.Value ? default(DateTime) : ds.Tables[0].Rows[0]["LastModifiedTime"]);
            }
            catch (Exception ex)
            {
                return null;
            }
            return ret;
        }
        static public DataTable Select(BillAO ao)
        {
            DataSet ds;
            try
            {
                SqlParameter[] Params =
                {
                    new SqlParameter("@ID",SqlDbType.BigInt)
                    , new SqlParameter("@Status",SqlDbType.Bit)
                    , new SqlParameter("@BAID",SqlDbType.BigInt)
                    , new SqlParameter("@PhieuKhamID",SqlDbType.BigInt)
                    , new SqlParameter("@ThuNganID",SqlDbType.Int)
                    , new SqlParameter("@Ngay",SqlDbType.DateTime)
                    , new SqlParameter("@SoTien",SqlDbType.Decimal)
                    , new SqlParameter("@LyDo",SqlDbType.NVarChar)
                    , new SqlParameter("@GhiChu",SqlDbType.NVarChar)
                    , new SqlParameter("@CreatedBy",SqlDbType.Int)
                    , new SqlParameter("@CreatedTime",SqlDbType.DateTime)
                    , new SqlParameter("@LastModifiedBy",SqlDbType.Int)
                    , new SqlParameter("@LastModifiedTime",SqlDbType.DateTime)
                };
                if (ao.ID != default(long))
                {
                    Params[0].Value = ao.ID;
                }
                else
                {
                    Params[0].Value = DBNull.Value;
                }
                if (ao.Status != default(bool))
                {
                    Params[1].Value = ao.Status;
                }
                else
                {
                    Params[1].Value = DBNull.Value;
                }
                if (ao.BAID != default(long))
                {
                    Params[2].Value = ao.BAID;
                }
                else
                {
                    Params[2].Value = DBNull.Value;
                }
                if (ao.PhieuKhamID != default(long))
                {
                    Params[3].Value = ao.PhieuKhamID;
                }
                else
                {
                    Params[3].Value = DBNull.Value;
                }
                if (ao.ThuNganID != default(int))
                {
                    Params[4].Value = ao.ThuNganID;
                }
                else
                {
                    Params[4].Value = DBNull.Value;
                }
                if (ao.Ngay != default(DateTime))
                {
                    Params[5].Value = ao.Ngay;
                }
                else
                {
                    Params[5].Value = DBNull.Value;
                }
                if (ao.SoTien != default(decimal))
                {
                    Params[6].Value = ao.SoTien;
                }
                else
                {
                    Params[6].Value = DBNull.Value;
                }
                if (ao.LyDo != default(string))
                {
                    Params[7].Value = ao.LyDo;
                }
                else
                {
                    Params[7].Value = DBNull.Value;
                }
                if (ao.GhiChu != default(string))
                {
                    Params[8].Value = ao.GhiChu;
                }
                else
                {
                    Params[8].Value = DBNull.Value;
                }
                if (ao.CreatedBy != default(int))
                {
                    Params[9].Value = ao.CreatedBy;
                }
                else
                {
                    Params[9].Value = DBNull.Value;
                }
                if (ao.CreatedTime != default(DateTime))
                {
                    Params[10].Value = ao.CreatedTime;
                }
                else
                {
                    Params[10].Value = DBNull.Value;
                }
                if (ao.LastModifiedBy != default(int))
                {
                    Params[11].Value = ao.LastModifiedBy;
                }
                else
                {
                    Params[11].Value = DBNull.Value;
                }
                if (ao.LastModifiedTime != default(DateTime))
                {
                    Params[12].Value = ao.LastModifiedTime;
                }
                else
                {
                    Params[12].Value = DBNull.Value;
                }
                ds = SqlHelper.ExecuteDataset(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_Select", Params);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        static public DataTable SelectWildcart(string wildCart)
        {
            DataSet ds;
            try
            {
                SqlParameter[] Params =
                {
                    new SqlParameter("@wildCart",wildCart)
                };
                ds = SqlHelper.ExecuteDataset(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_SelectWildCart", Params);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        static public int SelectCount(BillAO ao)
        {
            DataSet ds;
            try
            {
                SqlParameter[] Params =
                {
                    new SqlParameter("@ID",SqlDbType.BigInt)
                    , new SqlParameter("@Status",SqlDbType.Bit)
                    , new SqlParameter("@BAID",SqlDbType.BigInt)
                    , new SqlParmeter("@Ngay",SqlDbType.DateTime)
                    , new SqlParamameter("@PhieuKhamID",SqlDbType.BigInt)
                    , new SqlParameter("@ThuNganID",SqlDbType.Int)
                    , new SqlParaeter("@SoTien",SqlDbType.Decimal)
                    , new SqlParameter("@LyDo",SqlDbType.NVarChar)
                    , new SqlParameter("@GhiChu",SqlDbType.NVarChar)
                    , new SqlParameter("@CreatedBy",SqlDbType.Int)
                    , new SqlParameter("@CreatedTime",SqlDbType.DateTime)
                    , new SqlParameter("@LastModifiedBy",SqlDbType.Int)
                    , new SqlParameter("@LastModifiedTime",SqlDbType.DateTime)
                };
                if (ao.ID != default(long))
                {
                    Params[0].Value = ao.ID;
                }
                else
                {
                    Params[0].Value = DBNull.Value;
                }
                if (ao.Status != default(bool))
                {
                    Params[1].Value = ao.Status;
                }
                else
                {
                    Params[1].Value = DBNull.Value;
                }
                if (ao.BAID != default(long))
                {
                    Params[2].Value = ao.BAID;
                }
                else
                {
                    Params[2].Value = DBNull.Value;
                }
                if (ao.PhieuKhamID != default(long))
                {
                    Params[3].Value = ao.PhieuKhamID;
                }
                else
                {
                    Params[3].Value = DBNull.Value;
                }
                if (ao.ThuNganID != default(int))
                {
                    Params[4].Value = ao.ThuNganID;
                }
                else
                {
                    Params[4].Value = DBNull.Value;
                }
                if (ao.Ngay != default(DateTime))
                {
                    Params[5].Value = ao.Ngay;
                }
                else
                {
                    Params[5].Value = DBNull.Value;
                }
                if (ao.SoTien != default(decimal))
                {
                    Params[6].Value = ao.SoTien;
                }
                else
                {
                    Params[6].Value = DBNull.Value;
                }
                if (ao.LyDo != default(string))
                {
                    Params[7].Value = ao.LyDo;
                }
                else
                {
                    Params[7].Value = DBNull.Value;
                }
                if (ao.GhiChu != default(string))
                {
                    Params[8].Value = ao.GhiChu;
                }
                else
                {
                    Params[8].Value = DBNull.Value;
                }
                if (ao.CreatedBy != default(int))
                {
                    Params[9].Value = ao.CreatedBy;
                }
                else
                {
                    Params[9].Value = DBNull.Value;
                }
                if (ao.CreatedTime != default(DateTime))
                {
                    Params[10].Value = ao.CreatedTime;
                }
                else
                {
                    Params[10].Value = DBNull.Value;
                }
                if (ao.LastModifiedBy != default(int))
                {
                    Params[11].Value = ao.LastModifiedBy;
                }
                else
                {
                    Params[11].Value = DBNull.Value;
                }
                if (ao.LastModifiedTime != default(DateTime))
                {
                    Params[12].Value = ao.LastModifiedTime;
                }
                else
                {
                    Params[12].Value = DBNull.Value;
                }
                return int.Parse(SqlHelper.ExecuteScalar(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_SelectCount", Params).ToString());
            }
            catch (Exception ex)
            {
                return -1;
            }
        }
        static public bool DeleteByID(long id)
        {
            try
            {
                SqlParameter[] Params = { new SqlParameter("@ID", id) };
                int result = SqlHelper.ExecuteNonQuery(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_DeleteByID", Params);
                return (result > 0);
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        static public int UpdateByID(BillAO ao)
        {
            try
            {
                SqlParameter[] Params =
                {
                    new SqlParameter("@ID",ao.ID)
                    , new SqlParameter("@Status",ao.Status)
                    , new SqlParameter("@BAID",ao.BAID)
                    , new SqlParameter("@PhieuKhamID",ao.PhieuKhamID)
                    , new SqlParameter("@ThuNganID",ao.ThuNganID)
                    , new SqlParameter("@Ngay",ao.Ngay)
                    , new SqlParameter("@SoTien",ao.SoTien)
                    , new SqlParameter("@LyDo",ao.LyDo)
                    , new SqlParameter("@GhiChu",ao.GhiChu)
                    , new SqlParameter("@CreatedBy",ao.CreatedBy)
                    , new SqlParameter("@CreatedTime",ao.CreatedTime)
                    , new SqlParameter("@LastModifiedBy",ao.LastModifiedBy)
                    , new SqlParameter("@LastModifiedTime",ao.LastModifiedTime)
                };
                int result = SqlHelper.ExecuteNonQuery(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_UpdateByID", Params);
                return result;
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("duplicate"))
                {
                    return -2;
                }
                return -1;
            }
        }
        static public bool Delete(string condition)
        {
            try
            {
                SqlParameter[] Params =
                {
                    new SqlParameter("@condition",condition)
                };
                int result = SqlHelper.ExecuteNonQuery(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_Delete", Params);
                return (result > 0);
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        static public bool Update(string setFields, string condition)
        {
            try
            {
                SqlParameter[] Params =
                {
                    new SqlParameter("@setFields",setFields)
                    ,new SqlParameter("@condition",condition)
                };
                int result = SqlHelper.ExecuteNonQuery(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_Update", Params);
                return (result > 0);
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}




-------------
Duoc pham | nguyen lieu duoc pham
post comment
     

Mr. Raj. You can download the samples attachment from above link.

Posted by Suthish Nair Mar 30, 2011

pls full coding send me mail. DataGridView - Insert, Update, Delete and Retrieve records using stored procedure. Thankyou Mr.suthish

Posted by bhagyaraj bruce Mar 30, 2011

you need to explore it. check for articles here, might get some help.

Posted by Suthish Nair Mar 01, 2011

Hi, Is there any way to add edit/delete links or buttons to the same column in data grid view.

Posted by Kiran Vidhate Mar 01, 2011

Create a new Windows Application Project, and add attached zipped files. Run the sql scripts. Build and run the project.

Posted by Suthish Nair Feb 12, 2011
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.