Click here to Skip to main content
Click here to Skip to main content

Add, Edit, and Delete in DataGridView with Paging

, 24 Jan 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
This article describes DataGridView manipulation like add, edit, and delete, with paging, and using asynchronous method calls.

Sample Image - DataGridView_manipulation.png


The article, or rather code snippet, demonstrates a simple application to insert, update, and delete using a DataGridView. The application uses an asynchronous architecture for most of the calls to the database. This is to show that without a hanging UI, we can allow the user to continue with his tasks. The application has the following outline:

  1. Get all SQL Server instances from the network.
  2. Get all databases from the selected instance.
  3. If the user provides an empty user name or password, or a wrong user name or password, the same list of SQL Server instances will be returned. The code is available here[^].

  4. Get all tables from the selected database.
  5. Get all records from selected table.
  6. Add, edit, delete records from the DataGridView.
  7. A paging feature with number of records per page is also provided.

Asynchronous architecture

The application uses an async calling mechanism to make database calls. As the SQLEnumerator does not support async calling, I have added delegates to call those methods asynchronously. In .NET 2.0, the SqlCommand object supports async calling to a database. I am using this feature to get all the tables from the selected database. Delegates are the best practices to design async architectures because most of the things are internally handled by the CLR, and we do not have to bother much about them.

Application structure

When we start reading the code from the beginning, we can see that there is an enum named CallFor. This is used to set a private variable called when making calls to a SQL Server list, databases, and tables. This is done because only one call back method handles all the callbacks from asyn calls. A switch case statement manages the behavior of different callbacks. I have designed this application using a SqlCommandBuilder as I have some queries regarding how to use SqlCommandBuilder. The builder will automatically generate the insert, update, and delete commands, provided that you select the primary key in your Select query. I have faced a very common problem of cross thread exceptions. But, in my previous project, we implemented the same architecture, and .NET 2.0 provides InvokeRequired and the Invoke() function to overcome this problem. We have to declare a delegate with a similar signature as the callback method and call the same method using the control's Invoke() method. This will push all the call stack to the parent thread from the executing thread, and put parent thread to work. You need to follow a sequence like:

  1. Get all SQL Server instances.
  2. Get all databases from the selected instance.
  3. Get all tables from the selected database.
  4. Load data from the selected table.
  5. Use paging to navigate.
  6. Add buttons like Add/Update, Commit, Delete to insert/update or delete. You can delete/update/insert multiple records.

Here are some code blocks I'll explain. This function sets the database objects required throughout the application. The sqlQuery is dynamically built.

private void SetDataObjects()
    connection = new SqlConnection(connectionString);
    command = new SqlCommand(sqlQuery, connection);
    adapter = new SqlDataAdapter(command);
    builder = new SqlCommandBuilder(adapter);
    ds = new DataSet("MainDataSet");
    tempDataSet = new DataSet("TempDataSet");

The two functions below load the data and bind it to a DataGridView. I was trying to bind a temporary DataTable object to the DataGridView and then update the main table. But, I was not able to do so. I used the adapter's Fill() method which takes a start record and the number of records as input parameters with the DataSet. I created a temporary DataSet to get the total records. I dispose it immediately. Instead of directly binding the data source to a DataGridView, I prefer to add columns manually and then let the rows to bind to them. This allows sorting, and in case we do not want to show any columns, we can do it here.

private void btnLoad_Click(object sender, EventArgs e)
    lblLoadedTable.Text = "Loading data from table " + cmbTables.Text.Trim();
    btnLoad.Enabled = false;
    this.Cursor = Cursors.WaitCursor;
        if (userTable != null)
        userDataGridView.DataSource = null;
        sqlQuery = "SELECT * FROM [" + cmbTables.Text.Trim() + "]";
        totalRecords = tempDataSet.Tables[0].Rows.Count;
        adapter.Fill(ds, 0, 5, cmbTables.Text.Trim());
        userTable = ds.Tables[cmbTables.Text.Trim()];
        foreach (DataColumn dc in userTable.Columns)
            DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
            column.DataPropertyName = dc.ColumnName;
            column.HeaderText = dc.ColumnName;
            column.Name = dc.ColumnName;
            column.SortMode = DataGridViewColumnSortMode.Automatic;
            column.ValueType = dc.DataType;
        lblLoadedTable.Text = "Data loaded from table: " + userTable.TableName;
        lblTotRecords.Text = "Total records: " + totalRecords;
        CreateTempTable(0, int.Parse(cmbNoOfRecords.Text.Trim()));

        btnPrevious.Enabled = true;
        btnFirst.Enabled = true;
        btnPrevious.Enabled = true;
        btnNext.Enabled = true;
        btnLast.Enabled = true;
        btnAdd.Enabled = true;
        btnUpdate.Enabled = true;
        btnDelete.Enabled = true;
        cmbNoOfRecords.Enabled = true;
    catch (Exception ex)
        btnLoad.Enabled = true;
        this.Cursor = Cursors.Default;
        prgProgress.Value = 0;

This method actually binds the data to the DataGridView and is called for all paging functions. Depending upon the current index and all, the required number of records are fetched.

private void CreateTempTable(int startRecord, int noOfRecords)
    if (startRecord == 0 || startRecord < 0)
        btnPrevious.Enabled = false;
        startRecord = 0;
    int endRecord = startRecord + noOfRecords;
    if (endRecord >= totalRecords)
        btnNext.Enabled = false;
        isLastPage = true;
        endRecord = totalRecords;
    currentPageStartRecord = startRecord;
    currentPageEndRecord = endRecord;
    lblPageNums.Text = "Records from " + startRecord + " to " 
        + endRecord+ " of " + totalRecords;
    currentIndex = endRecord;

        if (connection.State == ConnectionState.Closed)
        adapter.Fill(ds, startRecord, noOfRecords, cmbTables.Text.Trim());
        userTable = ds.Tables[cmbTables.Text.Trim()];
    catch (Exception ex)

    userDataGridView.DataSource = userTable.DefaultView;
    userDataGridView.AllowUserToResizeColumns = true;

Here is a sample method which gets SQL Server instances asynchronously. After BeginInvoke(), the user is free to perform any task. The callback function will catch the response. This is the way you can invoke a method asynchronously using a delegate.

private void btnLoadSqlServers_Click(object sender, EventArgs e)
    btnLoadSqlServers.Enabled = false;
    this.Cursor = Cursors.WaitCursor;
    called = CallFor.SqlServerList;
    intlDelg.BeginInvoke(new AsyncCallback(CallBackMethod), intlDelg);

Here is the callback method that will handle all the callbacks from the different methods. When you use an async architecture, the callback is always on a new thread other than the parent one. This new thread will not able to access the controls on the parent thread. Hence, we need to shift the call stack to the parent thread, and this can be done using control.InvokeRequired and control.Invoke(). The following method shows how to do that.

private void CallBackMethod(IAsyncResult result)
    if (this.InvokeRequired)
        this.Invoke(new AsyncDelegate(CallBackMethod), result);
            prgProgress.Value = prgProgress.Maximum;
            switch (called)
                case CallFor.SqlServerList:
                    string[] sqlServers = intlDelg.EndInvoke(result);
                    if (cmbSqlServers.Items.Count > 0)
                        cmbSqlServers.Sorted = true;
                        cmbSqlServers.SelectedIndex = 0;
                    this.Cursor = Cursors.Default;
                    btnLoadSqlServers.Enabled = true;
                case CallFor.SqlDataBases:
                    string[] sqlDatabases = intlDelg.EndInvoke(result);
                    if (cmbAllDataBases.Items.Count > 0)
                        cmbAllDataBases.Sorted = true;
                        cmbAllDataBases.SelectedIndex = 0;
                    this.Cursor = Cursors.Default;
                    btnGetAllDataBases.Enabled = true;
                case CallFor.SqlTables:
                    reader = command.EndExecuteReader(result);
                    while (reader.Read())
                    if (cmbTables.Items.Count > 0)
                        cmbTables.Sorted = true;
                        cmbTables.SelectedIndex = 0;
                        grpDataManipulate.Enabled = true;
                        grpDataManipulate.Enabled = false;
        catch (Exception ex)
            if (called == CallFor.SqlTables)
                btnGetAllTables.Enabled = true;
                this.Cursor = Cursors.Default;
            prgProgress.Value = 0;


This way, we can easily manipulate a DataGridView. The only this is we have to use the data source that is directly bound to the DataGridView. Async calling will be very efficient while loading huge data. Please let me know if you have any queries.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior) Symantec Services, Pune
India India
Dear Friends,
I'm from Pune and currently working with Symantec. I'm having 7+ yrs of software development experience and I'm working on .NET since 6+ years.
I'm a Brainbench Certified Software Engineer in C#, ASP.NET, .NET Framework and ADO.NET.

Comments and Discussions

Questionuser control toolbar dll PinmemberMahesh_Bhosale15-Mar-13 20:53 
GeneralMy vote of 5 PinmemberPrasad_Kulkarni3-Jun-12 20:39 
BugGetting an Error when clicked on Commit Or Delete PinmemberRavindra.P.C25-Apr-12 0:11 
Questionvery good work and really appreciable effort Pinmembernaveen bansal28-Feb-12 11:48 
GeneralMy Vote of 5 PinmemberRaviRanjankr28-Nov-11 9:41 
GeneralMy vote of 5 PinmemberPKamaji4-Nov-11 21:13 
GeneralMy vote of 4 PinmemberEswa7-Nov-10 16:57 
GeneralMy vote of 5 Pinmembercbragdon10-Oct-10 3:00 
GeneralMy vote of 4 Pinmembernelgnut17-Aug-10 21:49 
Generaloptimized paging PinmemberP0110X12-Mar-10 4:55 
GeneralGood example for learners PinmemberMember 36709574-Jun-09 1:54 
GeneralRe: Good example for learners Pinmemberjdkulkarni5-Jun-09 3:46 
GeneralReally useful Pinmembers.s.cheral3-May-09 21:51 
GeneralRe: Really useful Pinmemberjdkulkarni5-Jun-09 3:46 
GeneralTanks really good Pinmemberdaitel14-Feb-09 21:40 
GeneralRe: Tanks really good Pinmemberjdkulkarni5-Jun-09 3:47 
QuestionCan u upload same code for VB.Net (Visual Basic)? PinmemberRoopeshMandloi4-Jan-09 18:55 
QuestionHow to edit data in datagridview in windows application Pinmembersrinivassam2-Apr-08 3:30 
QuestionDeleting problem PinmemberKillerman-14-Mar-08 8:57 
AnswerRe: Deleting problem PinmemberKillerman-14-Mar-08 11:24 
GeneralRe: Deleting problem PinmemberMember 767259828-May-13 5:27 
GeneralThanks Pinmembernsdlsandy4-Jan-08 6:48 
GeneralReally Good One PinmemberRRPKannan8-Nov-07 20:08 
QuestionJust 1 Question! Pinmember4n7JuK31-Oct-07 2:58 
AnswerRe: Just 1 Question! Pinmemberjdkulkarni5-Jun-09 3:50 
GeneralDatagrid Update,Insert,Delete,Cancel. Pinmembersomagunasekaran7-Sep-07 21:48 
GeneralRe: Datagrid Update,Insert,Delete,Cancel. Pinmemberjdkulkarni9-Sep-07 22:57 
Questionhow to load data in datagridview? Pinmemberlildiapaz13-Aug-07 17:23 
AnswerRe: how to load data in datagridview? Pinmemberjdkulkarni15-Aug-07 7:30 
Generalupdating multiple tables with datagridview Pinmemberjayvaishnav8212-Jul-07 0:08 
Questiondatagridview save to excel format Pinmemberhithread13-Jun-07 17:32 
AnswerRe: datagridview save to excel format Pinmemberjdkulkarni14-Jun-07 2:01 
Check if this can help you.
The foloowing Class takes a dataGridView and turn it into a recordset (adodb). It then formats the recordset before it exports it to excel.


You will need to reference the Microsoft Excel Object Library in the project first. Then Add a bound dataGridview to a form and a command button. Then add the below Class "clsExcelReport" to the project.

Name the datagrid "DataGridResults"

Name the button btnExcelReport and the copy and paste the following Sub "btnExcelReport_Click"

Private Sub btnExcelReport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExcelReport.Click

Dim clsExcelReport As New clsExcelReport


clsExcelReport.openExcelReport(DataGridResults, False, True)

Catch ex As Exception

End Try

End Sub


Option Strict Off

Public Class clsExcelReport

Private Function CreateRecordsetFromDataGrid(ByVal DGV As DataGridView) As ADODB.Recordset

Dim rs As New ADODB.Recordset

'Create columns in ADODB.Recordset

Dim FieldAttr As ADODB.FieldAttributeEnum

FieldAttr = ADODB.FieldAttributeEnum.adFldIsNullable Or ADODB.FieldAttributeEnum.adFldIsNullable Or ADODB.FieldAttributeEnum.adFldUpdatable

For Each iColumn As DataGridViewColumn In DGV.Columns

'only add Visible columns

If iColumn.Visible = True Then

Dim FieldType As ADODB.DataTypeEnum

'select dataType

If iColumn.ValueType Is GetType(Boolean) Then

FieldType = ADODB.DataTypeEnum.adBoolean

ElseIf iColumn.ValueType Is GetType(Byte) Then

FieldType = ADODB.DataTypeEnum.adTinyInt

ElseIf iColumn.ValueType Is GetType(Int16) Then

FieldType = ADODB.DataTypeEnum.adSmallInt

ElseIf iColumn.ValueType Is GetType(Int32) Then

FieldType = ADODB.DataTypeEnum.adInteger

ElseIf iColumn.ValueType Is GetType(Int64) Then

FieldType = ADODB.DataTypeEnum.adBigInt

ElseIf iColumn.ValueType Is GetType(Single) Then

FieldType = ADODB.DataTypeEnum.adSingle

ElseIf iColumn.ValueType Is GetType(Double) Then

FieldType = ADODB.DataTypeEnum.adDouble

ElseIf iColumn.ValueType Is GetType(Decimal) Then

FieldType = ADODB.DataTypeEnum.adCurrency

ElseIf iColumn.ValueType Is GetType(DateTime) Then

FieldType = ADODB.DataTypeEnum.adDBDate

ElseIf iColumn.ValueType Is GetType(Char) Then

FieldType = ADODB.DataTypeEnum.adChar

ElseIf iColumn.ValueType Is GetType(String) Then

FieldType = ADODB.DataTypeEnum.adVarWChar

End If

If FieldType = ADODB.DataTypeEnum.adVarWChar Then

rs.Fields.Append(iColumn.Name, FieldType, 300)


rs.Fields.Append(iColumn.Name, FieldType)

End If

rs.Fields(iColumn.Name).Attributes = FieldAttr

End If


'Opens the ADODB.Recordset


'Inserts rows into the recordset

For Each iRow As DataGridViewRow In DGV.Rows


For Each iColumn As DataGridViewColumn In DGV.Columns

'only add values for Visible columns

If iColumn.Visible = True Then

If iRow.Cells(iColumn.Name).Value.ToString = "" Then

If (rs(iColumn.Name).Attributes And ADODB.FieldAttributeEnum.adFldIsNullable) <> 0 Then

rs(iColumn.Name).Value = DBNull.Value

End If


rs(iColumn.Name).Value = iRow.Cells(iColumn.Name).Value

End If

End If



'Moves to the first record in recordset

If Not rs.BOF Then rs.MoveFirst()

Return rs

End Function

Public Sub openExcelReport(ByRef DGV As DataGridView, _

Optional ByVal bolSave As Boolean = False, _

Optional ByVal bolOpen As Boolean = True)

Dim xlApp As New Microsoft.Office.Interop.Excel.Application

Dim xlBook As Microsoft.Office.Interop.Excel.Workbook

Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet

Dim rs As New ADODB.Recordset

Dim xlrow As Integer

Dim strColType() As String


'opening connections to excel

xlBook = xlApp.Workbooks.Add

xlSheet = xlBook.Worksheets.Add()

If bolOpen = True Then

xlApp.Application.Visible = True

End If

xlrow = 1


xlSheet.Columns.HorizontalAlignment = 2

'formating the output of the report

xlSheet.Columns.Font.Name = "Times New Roman"

xlSheet.Rows.Item(xlrow).Font.Bold = 1

xlSheet.Rows.Item(xlrow).Interior.ColorIndex = 15

rs = CreateRecordsetFromDataGrid(DGV)

If rs.State = 0 Then rs.Open()



End Try

ReDim strColType(rs.Fields.Count)

For j As Integer = 0 To rs.Fields.Count - 1

xlSheet.Cells.Item(xlrow, j + 1) = rs.Fields.Item(j).Name

xlSheet.Cells(xlrow, j + 1).BorderAround(1, ColorIndex:=16, Weight:=2)

Next j

'This does a simple test to see if the of excel held by the user is 2000 or later

'This is needed because "CopyFromRecordset" only works with excel 2000 or later

xlrow = 2

If Val(Mid(xlApp.Version, 1, InStr(1, xlApp.Version, ".") - 1)) > 8 Then

xlSheet.Range("A" & xlrow).CopyFromRecordset(rs)


MessageBox.Show("You must use excel 2000 or above, opperation can not continue", "Excel Report", _

MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)


End If

Dim strSearch As String = ""

Dim strTemp As String = ""

For j As Integer = 0 To rs.Fields.Count - 1


'debug.Print(rs.Fields.Item(j).Type.ToString) 'finds out the format of the field

If rs.Fields.Item(j).Type.ToString = "adBigInt" Then 'these if statements are used to select which format to use

strSearch = "0;[Red]0"

ElseIf rs.Fields.Item(j).Type.ToString = "adVarChar" Then

strSearch = "@"

ElseIf rs.Fields.Item(j).Type.ToString = "adDouble" Then 'type float/double

strSearch = "0.00_ ;[Red]-0.00"

ElseIf rs.Fields.Item(j).Type.ToString = "adCurrency" Then 'money

strTemp = j & " " & strTemp 'used to keep track of currency for sum

strSearch = "€#,##0.00;[Red]-€#,##0.00"

ElseIf rs.Fields.Item(j).Type.ToString = "11" Then

strSearch = "@"

ElseIf rs.Fields.Item(j).Type.ToString = "adDBTimeStamp" Then 'type date/time

If rs.Fields.Item(j).Name.Contains("Date") = True Then

strSearch = "[$-1809]ddd, dd-mmm-yyyy;@"


strSearch = "h:mm AM/PM"

End If


strSearch = "@"

End If

xlSheet.Columns(j + 1).NumberFormat = strSearch

Next j

If strTemp.Length > 0 Then

Dim arrayStr() As String = Split(strTemp, " ")

Dim X As Integer

Dim lngLenght As Integer

For i As Integer = UBound(arrayStr) To 0 Step -1

'Asc (UCase$(Chr(KeyAscii)))

lngLenght = InStr(1, strTemp, " ")

If lngLenght > 0 Then

X = CInt(Left(strTemp, lngLenght - 1))

lngLenght = Len(strTemp) - lngLenght

strTemp = Right(strTemp, lngLenght)

End If

'debug.Print X

If X >= 26 Then

X = X - 26

arrayStr(i) = "A" & Chr(X + 65)


arrayStr(i) = Chr(X + 65)

End If

'debug.Print arrayStr(i)

xlSheet.Cells.Item(CInt(rs.RecordCount + 6), arrayStr(i)).Font.Bold = 1

xlSheet.Cells.Item(CInt(rs.RecordCount + 6), arrayStr(i)) = "=SUM(" & _

arrayStr(i) & xlrow & _

":" & arrayStr(i) & CInt(rs.RecordCount + 4) & ")"

Next i

End If

'some more formatting of the excel sheet. Thsi formats the way the

'sheet looks in print preview

xlSheet.PageSetup.LeftHeader = "&[Page]" & " of " & "&[Pages]"

xlSheet.PageSetup.RightHeader = "&[Date]" & " &[Time]"

xlSheet.PageSetup.HeaderMargin = 5

xlSheet.PageSetup.BottomMargin = 5

xlSheet.PageSetup.LeftMargin = 5

xlSheet.PageSetup.RightMargin = 5

xlSheet.PageSetup.TopMargin = 25



xlApp.UserControl = True

If bolOpen = False Then

xlApp.DisplayAlerts = False

xlBook.Close(True, Application.StartupPath & "\Excel\AVCDDUpdate.xls")


ElseIf bolSave = True Then

xlApp.DisplayAlerts = False

xlBook.SaveAs(Application.StartupPath & "\Excel\AVCDDUpdate.xls")

xlApp.DisplayAlerts = True

End If

Catch ex As Exception

Call errLogger(ex)

End Try


xlSheet = Nothing

xlBook = Nothing

xlApp = Nothing

End Sub

End Class

The link is[^]

Knowledge is power...
Questioncan u help me in gridview(edit,upadte,insert) with example Pinmembercrmanikandan19861-Jun-07 14:57 
Generalautomatic display in grid Pinmemberanjulla17-May-07 3:34 
GeneralRe: automatic display in grid Pinmemberjdkulkarni17-May-07 3:45 
GeneralRe: automatic display in grid Pinmemberanjulla17-May-07 4:01 
GeneralRe: automatic display in grid Pinmemberjdkulkarni17-May-07 5:31 
GeneralRe: automatic display in grid Pinmemberanjulla17-May-07 4:05 
Generalthanks a lot for this work Pinmembercrmanikandan198623-Apr-07 8:24 
GeneralRe: thanks a lot for this work Pinmemberjdkulkarni21-May-07 3:59 
QuestionCan u help me? Pinmemberkts2005s17-Apr-07 14:35 
AnswerRe: Can u help me? Pinmemberjdkulkarni18-Apr-07 4:04 
GeneralRe: Can u help me? Pinmemberkts2005s19-Apr-07 3:01 
GeneralRe: Can u help me? Pinmemberkts2005s7-May-07 9:04 
GeneralRe: Can u help me? Pinmembermcpoo7268-May-08 19:40 
GeneralRe: Can u help me? Pinmemberpraveenkumar_mca6-Apr-09 22:12 
Questionhow to calculate data in gridview Pinmemberdani99el11-Apr-07 19:45 
AnswerRe: how to calculate data in gridview Pinmemberjdkulkarni11-Apr-07 20:21 
GeneralRe: how to calculate data in gridview Pinmemberdani99el11-Apr-07 21:46 
QuestionToo good, but one question Pinmemberraghavendra .K11-Apr-07 18:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150414.1 | Last Updated 25 Jan 2007
Article Copyright 2007 by jdkulkarni
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid