Wednesday, September 25, 2013

DataGridView Tutorial

DataGridView Tutorial

Learn to use a DataGridView in 5 minutes.  A sample project is provided to help. In this tutorial, I will give you some tips and some advice. It will be a crash course. At the end, you will have enough to learn by your own. I will do it in visual basic and I will use a WinForm Application to quickly cover the most of the subject and skip the boring stuff.

Lesson 1: insert a DataGridView inside your WinForm.

After your place your DataGridView inside your form, select it and click the little arrow on the top right corner.

Try to add significant name for each of your column. Make sure you could easily edentify them:

Add as many columns you want. For this example, I will only use TextBox inside the DataGridView, also called DataGridViewTextBoxColumn.

Step 2: filling the DataGridView

The basic element inside a DataGridView is the rows. It works like MS-Access. You can’t delete a cell. You have to works with rows (or lines depending how you call it).
Here is the interesting part on how to add a new row.

        Dim str(Me.DataGridView1.ColumnCount - 1) As String

        str(cName.Index) = "Peter"
        str(cSalary.Index) = "30 000$"
        str(cCity.Index) = "Toronto"
        str(cPhone.Index) = "123-456-7890"


Using the column name and his index to make sure you are putting the right information under the right column.

You could make a loop to fill your DatagridView faster, here is and example using random value:

        Dim oRandom As Random
        oRandom = New Random()

        Dim str(Me.DataGridView1.ColumnCount - 1) As String

        For index1 As Integer = 0 To 10
            str(cName.Index) = oRandom.Next(100).ToString
            str(cSalary.Index) = oRandom.Next(100).ToString
            str(cCity.Index) = oRandom.Next(100).ToString
            str(cPhone.Index) = oRandom.Next(100).ToString


Lesson 2 : Delete a row

Rows inside the DataGridView is just a regular collection. So all the common commands such as Remote, RemoveAt and Clear  are the same.

Here is a basic example to clear all your rows:


Lesson 3 : Insert a ContextMenuStrip

Using a ContextMenuStrip1 make the job easier for the user. Naturally, the user will right click the DataGridView to add, delete, move, copy, cut and paste inside the DataGridView. To do so, you need the get the rows number and the column number from the user.
Here is an example that displays the rows number and the column of the MouseClick cell. It will also display a ContextMenuStrip right at the place where the user clicks.

    Private Sub DataGridView1_CellMouseClick(sender As Object, e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick

        Me.Text = ("[" & e.RowIndex & " ; " & e.ColumnIndex & "]")

        Dim pt As Point = MousePosition

    End Sub

Lesson 4: Save your DataGridView

There is many ways to save your DatagridView. You could send the sata inside a SQL database. You could use a DataSet to save it inside a XML file. I will only show you how to save it inside a text file. Each value will be separated by a TAB.
Why am I showing you this way? Because is the simplest way and because most reader wan something simple.

    ''' <summary>
    ''' This is a sample of function from DataGridView to Text File
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SaveDataGridView()
        Dim strLine As String = ""
        Using oSaveFileDialog As New SaveFileDialog
            oSaveFileDialog.Title = "save your DataGridView inside a text file"
            oSaveFileDialog.AddExtension = True
            oSaveFileDialog.DefaultExt = "txt"
            If oSaveFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
                Using oFile As New IO.StreamWriter(oSaveFileDialog.FileName, False)
                    For index1 As Integer = 0 To Me.DataGridView1.RowCount - 1
                        strLine = ""
                        For index2 As Integer = 0 To Me.DataGridView1.Rows(index1).Cells.Count - 1
                            strLine = strLine & vbTab & Me.DataGridView1.Rows(index1).Cells(index2).Value
                End Using

            End If
        End Using

    End Sub

Download the sample project

All the functions and the step use in this post are inside the sample project. Fell free to take a look at it. When you start the sample project, an initial DataGridView will be filled with random numbers. A save function is called if you close the WinForm.


  1. This brief introduction to the DataGridView class was very helpful. All the other tutorials start at a higher level, so this was perfect for a newbie like me doing it with VB.NET while transitioning from VB6 (yeah, I know, what took so long? -- Been away from VB programming for several years). The typo's were a little annoying and the heading Delete A Row deletes all rows.

    For a brief intro this did the trick!