Bind and Show a ComboBox in a DataGridView Cell – Windows Application (C# and Vb.Net)

A DataGridView control in .Net is perfect for showing data in a tabular format. Its use is not limited to just displaying data, but it’s a perfect tool for doing data manipulation by binding it with a database. With its many useful features, you can make the DataGridView to perform like an Excel spreadsheet.

Updated: I have now added code for C#. Along with it, I have also explained how to set the name property of each column in the DataGridView and its proper usage.

ComboBox in DataGridView

In this article, I am going to show you how to bind a .Net ComboBox control with a DataGridView. The ComboBox will show up in a Cell of a particular column when focus sets on that column. The combo box will allow the user to select value from a list of pre-define of items.

Also Read: Windows Forms CheckedListBox Control – C# and Vb.Net

Start Microsoft Visual Studio and select a New Project from the File menu (Left Top Menu). From New Project templates, select Windows Forms Application and click OK.

01) A new project appears with a Blank Form. Click the Toolbox button and from the list of tools Double Click to add a DataGridView control on the form.

02) Select the DataGridView control and right click the mouse to choose Properties. In the Properties window, find the Columns property and open it. Add few columns to the Grid. (See the below Image).

To add the columns, you simply have to click the Add button, which will open the Add Column window. You will have to add values to the first and last fields, that is, Name and Header Text.

Please remember, the Present Address column is important for this example to work properly. Therefore, in the Header Text field add the text Present Address and in the Name field add PresentAddress (without any space).

DataGridView Design Mode

03) Finally drag and drop a ComboBox control on the DataGridView. The ComboBox will have a list of Qualifications. So add a few items in the ComboBox. To add the values, right click the control and choose Properties. Find the Items property and add items to it.
Next, set the Visible property of the ComboBox as False. We don’t want the ComboBox to be visible when the form loads. The ComboBox will show up when the focus is on a Cell corresponding to the Qualification Column. Until then, it remains hidden.

Note: The “ComboBox” control should be placed on the “DataGridView” control.

Now, let’s write the code.

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class frmDataGridView_Demo : Form
    {
        DataTable dtTable = new DataTable("Employee");      // CREATE A DATATABLE.

        public frmDataGridView_Demo()
        {
            InitializeComponent();
            AddRows();             // ADD FEW BLANK ROWS TO START WITH.
        }

        private void AddRows()
        {
            DataRow row = null;
            row = dtTable.NewRow();

            int iCntCol = 0;

            for (iCntCol = 1; iCntCol <= 10; iCntCol++)
            {
                row = dtTable.NewRow();     // ADD BLANK ROWS TO THE DATATABLE.
                dtTable.Rows.Add(row);
            }

            // ADD DATATABLE TO GRID. (WITH THE BLANK ROWS)
            dataGridView1.DataSource = dtTable;

            // ADD SOME COLOR TO THE GRID.
            dataGridView1.GridColor = Color.FromArgb(211, 222, 229);
            dataGridView1.BackgroundColor = Color.Wheat;

            dataGridView1.RowsDefaultCellStyle.BackColor = Color.AliceBlue;
            dataGridView1.RowsDefaultCellStyle.SelectionBackColor = Color.CornflowerBlue;
            dataGridView1.RowsDefaultCellStyle.SelectionForeColor = Color.White;
        }

        // CONTROL THE KEY STROKES.
        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, 
            System.Windows.Forms.Keys keyData)
        {
            if (keyData == Keys.Enter)
            {
                // ON ENTER KEY, GO TO THE NEXT CELL. 
                // WHEN THE CURSOR REACHES THE LAST COLUMN, CARRY IT ON TO THE NEXT ROW.

                if (ActiveControl.Name == "DataGridView1")
                {
                    // CHECK IF ITS THE LAST COLUMN
                    if (dataGridView1.CurrentCell.ColumnIndex == dataGridView1.ColumnCount - 1)
                    {
                        // GO TO THE FIRST COLUMN, NEXT ROW.
                        dataGridView1.CurrentCell = 
                            dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex + 1]
                                .Cells[0];
                    }
                    else
                    {
                        // NEXT COLUMN.
                        dataGridView1.CurrentCell = 
                            dataGridView1.Rows[dataGridView1.CurrentRow.Index]
                            .Cells[dataGridView1.CurrentCell.ColumnIndex + 1];
                    }

                    return true;
                }
                else if (ActiveControl is DataGridViewTextBoxEditingControl)
                {
                    // SHOW THE COMBOBOX WHEN FOCUS IS ON A CELL 
                        CORRESPONDING TO THE "QUALIFICATION" COLUMN.
                    if (dataGridView1.Columns
                        [dataGridView1.CurrentCell.ColumnIndex].Name == "PresentAddress")
                    {
                        dataGridView1.CurrentCell = 
                            dataGridView1.Rows[dataGridView1.CurrentRow.Index]
                                .Cells[dataGridView1.CurrentCell.ColumnIndex + 1];

                        // SHOW COMBOBOX.
                        Show_Combobox(dataGridView1.CurrentRow.Index, 
                            dataGridView1.CurrentCell.ColumnIndex); 

                        SendKeys.Send("{F4}");      // DROP DOWN THE LIST.
                        return true;
                    }
                    else
                    {
                        // CHECK IF ITS THE LAST COLUMN.
                        if (dataGridView1.CurrentCell.ColumnIndex == 
                            dataGridView1.ColumnCount - 1)
                        {
                            // GO TO THE FIRST COLUMN, NEXT ROW.
                            dataGridView1.CurrentCell = 
                                dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex + 1]
                                    .Cells[0];
                        }
                        else
                        {
                            // NEXT COLUMN.
                            dataGridView1.CurrentCell = 
                                dataGridView1.Rows[dataGridView1.CurrentRow.Index]
                                    .Cells[dataGridView1.CurrentCell.ColumnIndex + 1];
                        }
                        return true;
                    }
                }
                else if (ActiveControl.Name == "ComboBox1")
                {
                    // HIDE THE COMBOBOX AND ASSIGN COMBO'S VALUE TO THE CELL.
                    comboBox1.Visible = false;

                    dataGridView1.Focus();

                    // ONCE THE COMBO IS SET AS INVISIBLE, SET FOCUS BACK TO THE GRID. 
                        (IMPORTANT)
                    dataGridView1[dataGridView1.CurrentCell.ColumnIndex, 
                        dataGridView1.CurrentRow.Index].Value = comboBox1.Text;

                    dataGridView1.CurrentCell = 
                        dataGridView1.Rows[dataGridView1.CurrentRow.Index]
                            .Cells[dataGridView1.CurrentCell.ColumnIndex + 1];
                }
                else
                {
                    SendKeys.Send("{TAB}");
                }
                return true;
            }
            else if (keyData == Keys.Escape)            // PRESS ESCAPE TO HIDE THE COMBOBOX.
            {
                if (ActiveControl.Name == "ComboBox1")
                {
                    comboBox1.Text = "";
                    comboBox1.Visible = false;

                    dataGridView1.CurrentCell = 
                        dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex]
                            .Cells[dataGridView1.CurrentCell.ColumnIndex];

                    dataGridView1.Focus();
                }
                return true;
            }
            else
            {
                return base.ProcessCmdKey(ref msg, keyData);
            }
        }

        private void Show_Combobox(int iRowIndex, int iColumnIndex)
        {
            // DESCRIPTION: SHOW THE COMBO BOX IN THE SELECTED CELL OF THE GRID.
            // PARAMETERS: iRowIndex - THE ROW ID OF THE GRID.
            //             iColumnIndex - THE COLUMN ID OF THE GRID.

            int x = 0;
            int y = 0;
            int Width = 0;
            int height = 0;

            // GET THE ACTIVE CELL'S DIMENTIONS TO BIND THE COMBOBOX WITH IT.
            Rectangle rect = default(Rectangle);
            rect = dataGridView1.GetCellDisplayRectangle(iColumnIndex, iRowIndex, false);
            x = rect.X + dataGridView1.Left;
            y = rect.Y + dataGridView1.Top;

            Width = rect.Width;
            height = rect.Height;

            comboBox1.SetBounds(x, y, Width, height);
            comboBox1.Visible = true;
            comboBox1.Focus();
        }
    }
}

Vb.Net
Option Explicit On

Public Class frmDataGridView_Demo
    Dim dtTable As New DataTable("Employee")    ' CREATE A DATATABLE.

    Private Sub frmDataGridView_Demo_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
            Handles Me.Load
        AddRows()                ' ADD FEW BLANK ROWS TO START WITH.
    End Sub

    Private Sub AddRows()
        Dim row As DataRow
        row = dtTable.NewRow

        For iCntCol = 1 To 10
            row = dtTable.NewRow        ' ADD BLANK ROWS TO THE DATATABLE.
            dtTable.Rows.Add(row)
        Next

        With DataGridView1
            .DataSource = dtTable       ' ADD DATATABLE TO GRID. (WITH THE BLANK ROWS)

            ' JUST FOR THE LOOKS.
            .GridColor = Color.FromArgb(211, 222, 229)
            .BackgroundColor = Color.Wheat

            .RowsDefaultCellStyle.BackColor = Color.AliceBlue
            .RowsDefaultCellStyle.SelectionBackColor = Color.CornflowerBlue
            .RowsDefaultCellStyle.SelectionForeColor = Color.White
        End With
    End Sub

    ' CONTROL THE KEY STROKES.
    Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, _
            ByVal keyData As System.Windows.Forms.Keys) As Boolean
        If keyData = Keys.Enter Then

            ' ON ENTER KEY, GO TO THE NEXT CELL. 
                ' WHEN THE CURSOR REACHES THE LAST COLUMN, CARRY IT ON TO THE NEXT ROW.

            If ActiveControl.Name = "DataGridView1" Then
                With DataGridView1
                    If .CurrentCell.ColumnIndex = .ColumnCount - 1 Then             ' CHECK IF ITS THE LAST COLUMN
                        .CurrentCell = .Rows(.CurrentCell.RowIndex + 1).Cells(0)    ' GO TO THE FIRST COLUMN, NEXT ROW.
                    Else
                        .CurrentCell = .Rows(.CurrentRow.Index).Cells(.CurrentCell.ColumnIndex + 1)     ' NEXT COLUMN.
                    End If
                End With

            ElseIf TypeOf ActiveControl Is DataGridViewTextBoxEditingControl Then

                ' SHOW THE COMBOBOX WHEN FOCUS IS ON A CELL CORRESPONDING TO THE "QUALIFICATION" COLUMN.
                With DataGridView1
                    If .Columns(.CurrentCell.ColumnIndex).Name = "PresentAddress" Then
                        .CurrentCell = .Rows(.CurrentRow.Index).Cells(.CurrentCell.ColumnIndex + 1)

                        ' SHOW COMBOBOX.
                        Show_Combobox(.CurrentRow.Index, .CurrentCell.ColumnIndex)
                        SendKeys.Send("{F4}")               ' DROP DOWN THE LIST.
                    Else
                        If .CurrentCell.ColumnIndex = .ColumnCount - 1 Then             ' CHECK IF ITS THE LAST COLUMN
                            .CurrentCell = .Rows(.CurrentCell.RowIndex + 1).Cells(0)    ' GO TO THE FIRST COLUMN, NEXT ROW.
                        Else
                            .CurrentCell = .Rows(.CurrentRow.Index).Cells(.CurrentCell.ColumnIndex + 1)     ' NEXT COLUMN.
                        End If
                    End If
                End With

            ElseIf ActiveControl.Name = "ComboBox1" Then
                ' HIDE THE COMBOBOX AND ASSIGN COMBO'S VALUE TO THE CELL.
                ComboBox1.Visible = False

                With DataGridView1
                    .Focus()            ' ONCE THE COMBO IS SET AS INVISIBLE, SET FOCUS BACK TO THE GRID. (IMPORTANT)
                    .Item(.CurrentCell.ColumnIndex, .CurrentRow.Index).Value = Trim(ComboBox1.Text)
                    .CurrentCell = .Rows(.CurrentRow.Index).Cells(.CurrentCell.ColumnIndex + 1)
                End With
            Else
                SendKeys.Send("{TAB}")
            End If
            Return True

        ElseIf keyData = Keys.Escape Then       ' PRESS ESCAPE TO HIDE THE COMBOBOX.
            If ActiveControl.Name = "ComboBox1" Then
                ComboBox1.Text = "" : ComboBox1.Visible = False

                With DataGridView1
                    .CurrentCell = .Rows(.CurrentCell.RowIndex).Cells(.CurrentCell.ColumnIndex)
                    .Focus()
                    Return True
                End With
            End If
        Else
            Return MyBase.ProcessCmdKey(msg, keyData)
        End If
    End Function

    Private Sub Show_Combobox(ByVal iRowIndex As Integer, ByVal iColumnIndex As Integer)
        ' DESCRIPTION: SHOW THE COMBO BOX IN THE SELECTED CELL OF THE GRID.
        ' PARAMETERS: iRowIndex - THE ROW ID OF THE GRID.
        '             iColumnIndex - THE COLUMN ID OF THE GRID.

        Dim x As Integer = 0
        Dim y As Integer = 0
        Dim Width As Integer = 0
        Dim height As Integer = 0

        ' GET THE ACTIVE CELL'S DIMENTIONS TO BIND THE COMBOBOX WITH IT.
        Dim rect As Rectangle
        rect = DataGridView1.GetCellDisplayRectangle(iColumnIndex, iRowIndex, False)
        x = rect.X + DataGridView1.Left
        y = rect.Y + DataGridView1.Top

        Width = rect.Width
        height = rect.Height

        With ComboBox1
            .SetBounds(x, y, Width, height)
            .Visible = True
            .Focus()
        End With
    End Sub
End Class

Related Article: Copy Data from One DataGridView to Another using C# and Vb.Net

Tweet this article Facebook Google+
comments powered by Disqus

Join our Google Plus Community and be a part of a discussion!