Click here to Skip to main content
Click here to Skip to main content
Go to top

How to Use a Custom Grid with ComboBox Columns

, 10 Feb 2014
Rate this:
Please Sign up or sign in to vote.
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

License

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

Share

About the Author

Alexey Shtykov
Software Developer (Senior)
Russian Federation Russian Federation
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 10 Feb 2014
Article Copyright 2014 by Alexey Shtykov
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid