65.9K
CodeProject is changing. Read more.
Home

How to Use a Custom Grid with ComboBox Columns

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Feb 10, 2014

CPOL
viewsIcon

10301

DataGridView and ComboBox

Introduction

I'm a lazy person. I don't want to write a lot of code, but sometimes I have to, especially when I try to use free software with Windows.

Background

This tip has been created after a long time while I'm trying to combine MySQL database and Microsoft Excel in one C# application for non-IT users.

Using the Code

This code has been created and tested in a custom DataGridView without underlining DataSource in Microsoft Visual C# 2010 (Express).

  1. Declare class for combo box item in your project. This class must have at least two properties (not a data member):
        class CBItemClass
        {
            long id;
            string name;
            public long ID
            {
                get { return id;}
                set {id = value;}
            }
            public string Name
            {
                get { return name; }
                set { name = value; }
            }
        } 
  2. Declare combo box source collection in your form:
        List<CBItemClass> xlCols2;
  3. Fill this collection with items you need (I assume that you create an instance for your data source before you try to fill it):
        CBItemClass o = new CBItemClass();
        xlCols2.Add(o);
  4. Prepare your DataGridView's column to use items you load:
        col.ValueMember = "ID"; // this property will be used as a key */
        col.DisplayMember = "Name";// this property will display to user even in drop down list
        col.DataSource = xlCols2; // connect collection with the column 
  5. And, when you need - you can set a value that you need in combo with similar code:
        CBItemClass o = new CBItemClass(); // create an item
        o.ID = ...; // set primary key
        o.Name = ...;// set display name
        dataGrid.Rows[1].Cells[1].Value = o; // set cell's value
  6. After all, you'll get a grid with your values.

Points of Interest

I wrote this tip after I spent half a day to search a solution for my issue.

History

  • 2014-02-10 17:50:00 : Initial post