65.9K
CodeProject is changing. Read more.
Home

Embedding a DataGridView in a ComboBox

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Jun 3, 2016

CPOL
viewsIcon

13603

downloadIcon

17

This is an alternative for "Embedding a DataGridView in a ComboBox"

Background

This project is based on the article, Embedding a DataGridView in a ComboBox, whose code is in VB.

Using the Code

Output of this project is a .dll file. You must attach this file in your project and use it like a control of Windows Forms.

Keep in Mind

  • You have to add a simple DataGridView in your project, this element will be controlled by GridComboBox, specially visibility states.

This is a small brief of how to use this component in your project:

using System;
using TemporalAPP.GraphicSourceDataSetTableAdapters;
using System.Data;
using System.Windows.Forms;
using static TemporalAPP.GraphicSourceDataSet;
using GridComboBox;

namespace TemporalAPP
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ArticuloArancelDataTable tabla = new ArticuloArancelDataTable();
            new ArticuloArancelTableAdapter().Fill(tabla);
            dataGridView1.DataSource = tabla; // whatever datasource of DataGridView
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.Columns[0].Width = 1;
            accGridComboBox1.AddDataGridView(dataGridView1, false); // SO IMPORTANT!
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            dataGridView1.Visible = true;
        }

        private void dataGridView1_CellMouseDoubleClick
                     (object sender, DataGridViewCellMouseEventArgs e)
        {
            if (accGridComboBox1.SelectedValue == null) return;
            accGridComboBox1.Text = 
               ((DataRowView)accGridComboBox1.SelectedValue).Row["Codigo"].ToString();
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Return || e.KeyCode == Keys.Enter)
            {
                if (accGridComboBox1.SelectedValue == null) return;
                accGridComboBox1.Text = 
                   ((DataRowView)accGridComboBox1.SelectedValue).Row["Codigo"].ToString();
            }
        }
    }

Important Notes

Default visibility state of DataGridView is true, so you have to do double click on GridComboBox control until it shrinks; after that, you can use it. I was considering it to be an issue.

First Run

After Initial Double Click

After Select an Item

Point of Interest

I would like if someone can help with the initial state of the DataGridView. In my opinion, it would be better with visibility=false; to avoid initial double click.

History

  • 3rd June, 2016: Initial version