Click here to Skip to main content
6,292,426 members and growing! (10,294 online)
Email Password   helpLost your password?
Desktop Development » Grid & Data Controls » Grid controls     Intermediate License: The Code Project Open License (CPOL)

ComboBox in a DataGrid

By René Paw Christensen

How to embed a ComboBox (DropDownList) in a DataGrid.
C#, Windows, .NET 1.1, Visual Studio, Dev
Posted:4 Jun 2004
Updated:13 Sep 2006
Views:203,896
Bookmarked:67 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
29 votes for this article.
Popularity: 5.30 Rating: 3.63 out of 5
4 votes, 13.8%
1
2 votes, 6.9%
2
5 votes, 17.2%
3
7 votes, 24.1%
4
11 votes, 37.9%
5

Introduction

I needed a ComboBox in my DataGrid. After looking around on the web, I found many examples, but none of them worked for me.

With inspiration from Alastair Stells' article here on The Code Project and whatever else I found on the Internet, I have made the following DataGridComboBoxColumn class.

Why did the other examples not work

All the other examples populate the ComboBox with a DataView, but I need to (want to be able to) populate my ComboBox with an IList (ArrayList) instead of a DataView.

columnComboBox = new DataGridComboBoxColumn();
columnComboBox.comboBox.DataSource = new ArrayList(MyDataClass.GetArray());
columnComboBox.comboBox.DisplayMember = "Name";
columnComboBox.comboBox.ValueMember = "GUID";

And MyDataClass.GetArray() returns MyDataClass[], and has two properties named Name and GUID.

The other examples expect columnComboBox.comboBox.DataSource to be a DataView, and it being an ArrayList generates exceptions.

I use the ComboBox to fetch display text

Since you don't know the type of columnComboBox.comboBox.DataSource, you can't use that to translate between the underlying data and what to display in the DataGrid.

Instead, I use the ComboBox itself, by overriding the ComboBox and implementing this method.

public string GetDisplayText(object value) {
   // Get the text.

   string text   = string.Empty;
   int  memIndex  = -1;
   try {
      base.BeginUpdate();
      memIndex     = base.SelectedIndex;
      base.SelectedValue = value.ToString();
      text      = base.SelectedItem.ToString();
      base.SelectedIndex = memIndex;
   } catch {
     return GetValueText(0);
   } finally {
      base.EndUpdate();
   }

   return text;
} // GetDisplayText

What I do is simple. I select the item which displays the text I want, get the text, and then reselect the original item. By doing it this way, it doesn't matter what data source is used.

Because I use the ComboBox itself to fetch the display text, the ComboBox must be populated before the DataGrid is drawn.

Alastair Stells noted about this in his article:

Another issue which arose was an eye-opener! I discovered the ComboBox does not get populated until the ComboBox.Visible property is set for the first time.

This means that the ComboBox can't be used to fetch the initial display text, because it is not visible when the DataGrid is first shown (painted).

I used a normal ComboBox to illustrate the problem and the solution.

ComboBox comboBox = new ComboBox();
comboBox.DataSource = new ArrayList(MyDataClass.GetArray());
comboBox.DisplayMember = "Name"
comboBox.ValueMember = "GUID"
MessageBox.Show(comboBox.Items.Count.ToString()); // THIS IS ALWAYS 0!

I learned that it didn't help to show the ComboBox, but instead I had to set its parent - which internally commits the data from the DataSource to the Items collection.

ComboBox comboBox = new ComboBox();
comboBox.Parent = this; // this is a Form instance in my case.

comboBox.DataSource = new ArrayList(MyDataClass.GetArray());
comboBox.DisplayMember = "Name"
comboBox.ValueMember = "GUID"
// THIS IS MyDataClass.GetArray().Count

MessageBox.Show(comboBox.Items.Count.ToString());

What else about my DataGridComboBoxColumn

The source code is straightforward. First, I inherited DataGridTextBoxColumn, but my class then evolved into inheriting DataGridColumnStyle. This meant that I had to implement the Paint methods, but at this point, I had some examples of that as well. I like the idea of not having an invisible TextBox behind it all.

How to use

Sadly, I don't know how to "register" my DataGridComboBoxColumn with the GridColumnStyles, enabling me to design the DataGrid columns in the designer. This code does it manually:

// Add three MyDataClass objects, to the DataGridComboBox.

// This is the choices which will apear in the ComboBox in the DataGrid.

// You can see in the source that the MyDataClass doubles

// as a static collection, where the new MyDataClass objects

// automatically is added.

// All the MyDataClass objects can be retreived in an array

// with the static method: MyDataClass.GetArray().

if (MyDataClass.GetArray().Length == 0) {
    new MyDataClass("Denmark");
    new MyDataClass("Faroe Islands (DK)");
    new MyDataClass("Finland");
    new MyDataClass("Greenland (DK)");
    new MyDataClass("Iceland");
    new MyDataClass("Norway");
    new MyDataClass("Sweden");
}


// I don't have a database here, so I make my

// own DataTable with two columns and finally

// populate it with some test rows.

DataTable table = new DataTable("TableOne");

DataColumn column = table.Columns.Add();
column.ColumnName = "country";
// Realy a GUID from the DataGridComboBox.

column.DataType = Type.GetType("System.Guid");

column = table.Columns.Add();
column.ColumnName = "notes";
column.DataType = Type.GetType("System.String");

table.Rows.Add(new object[] {MyDataClass.GetArray()[0].GUID, 
                             "Population 5.368.854"});
table.Rows.Add(new object[] {MyDataClass.GetArray()[1].GUID, 
                             "Population 46.011"});
table.Rows.Add(new object[] {MyDataClass.GetArray()[2].GUID, 
                             "Population 5.183.545"});
table.Rows.Add(new object[] {MyDataClass.GetArray()[3].GUID, 
                             "Population 56.376"});
table.Rows.Add(new object[] {MyDataClass.GetArray()[4].GUID, 
                             "Population 279.384"});
table.Rows.Add(new object[] {MyDataClass.GetArray()[5].GUID, 
                             "Population 4.525.116"});
table.Rows.Add(new object[] {MyDataClass.GetArray()[6].GUID, 
                             "Population 8.876.744"});

// Create a DataGridTableStyle object.

DataGridTableStyle tableStyle = new DataGridTableStyle();
DataGridTextBoxColumn columnTextBox;
DataGridComboBoxColumn columnComboBox;
tableStyle.RowHeadersVisible = true;
tableStyle.RowHeaderWidth = 20;

// Add customized columns.

// Column "notes", which is a simple text box.

columnTextBox = new DataGridTextBoxColumn();
columnTextBox.MappingName = "notes";
columnTextBox.HeaderText = "Country notes";
columnTextBox.Width = 200;
tableStyle.GridColumnStyles.Add(columnTextBox);

// Column "country", which is the ComboBox.

columnComboBox = new DataGridComboBoxColumn();
columnComboBox.comboBox.Parent = this; // Commit dataset.

columnComboBox.comboBox.DataSource = 
               new ArrayList(MyDataClass.GetArray());
columnComboBox.comboBox.DisplayMember = "name";
columnComboBox.comboBox.ValueMember = "GUID";
columnComboBox.MappingName = "country";
columnComboBox.HeaderText = "Country";
columnComboBox.Width = 200;
tableStyle.GridColumnStyles.Add(columnComboBox);

// Add the custom TableStyle to the DataGrid.

datagrid.TableStyles.Clear();
datagrid.TableStyles.Add(tableStyle);
datagrid.DataSource = table;
tableStyle.MappingName = "TableOne";

I think I have focused on a problem here: if you want a ComboBox in your DataGrid, and you want to populate the ComboBox with items from an array containing instances of your own class.

I hope someone finds it useful - enjoy.

Updated September 2006

A few bugs have been found in my source code. Apparently, someone still downloads and tries to use the source, even though .NET 2.0 has solved the problem with a ComboBox in a DataGrid. The new download contains the original source, plus a small VS project with the updated source code.

License

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

About the Author

René Paw Christensen


Member
See http://rpc-scandinavia.dk.
Occupation: Web Developer
Location: Denmark Denmark

Other popular Grid & Data Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 60 (Total in Forum: 60) (Refresh)FirstPrevNext
Generalcropping images Pinmembernace2k222:43 16 Jun '09  
Questioncombobox should hide after selecting value from combobox and selected value show in datagrid cell Pinmembernik4u21:02 21 Jan '09  
AnswerRe: combobox should hide after selecting value from combobox and selected value show in datagrid cell Pinmembernik4u23:17 21 Jan '09  
GeneralRe: combobox should hide after selecting value from combobox and selected value show in datagrid cell PinmemberRené Paw Christensen9:47 22 Jan '09  
GeneralThe Text is not empty, but the selectIndex is -1 Pinmemberdqddqq18:35 1 Nov '07  
GeneralRe: The Text is not empty, but the selectIndex is -1 Pinmemberdqddqq22:43 6 Nov '07  
GeneralWhy.... Pinmemberpatgrape19:21 30 Oct '07  
GeneralRe: Why.... PinmemberRené Paw Christensen7:35 31 Oct '07  
QuestionInsert Values dynamically? [modified] PinmemberMaYo691:11 6 Sep '07  
QuestionUpdate cell content with the selected index of the ComboBox Pinmemberlaurentma9223:59 15 Apr '07  
AnswerRe: Update cell content with the selected index of the ComboBox Pinmemberlaurentma924:31 16 Apr '07  
QuestionIt is not working PinmemberDeltaSoft20:34 10 Apr '07  
QuestionHow to get the selected value in the combobox Pinmembermax845:25 25 Mar '07  
AnswerRe: How to get the selected value in the combobox Pinmemberlaurentma924:24 16 Apr '07  
GeneralProblem with Focus on the GridComboBox Pinmemberraj30sep7:20 7 Nov '06  
GeneralNew row always has first element in combobox selected PinmemberDensi8:14 24 Oct '06  
GeneralRe: New row always has first element in combobox selected PinmemberDensi9:39 25 Oct '06  
GeneralRe: New row always has first element in combobox selected Pinmemberdqddqq21:25 1 Nov '07  
GeneralCurrentCellChanged Pinmembervaishali1022:26 17 Sep '06  
GeneralCombo Selection Change Event. Pinmemberramya.venkateswaran@gmail.com21:50 17 Sep '06  
GeneralSOURCE: Form1.cs PinmemberRené Paw Christensen6:21 12 Sep '06  
GeneralSOURCE: DataGridComboBoxColumn.cs PinmemberRené Paw Christensen6:17 12 Sep '06  
GeneralDataGridComboBox Working fine Pinmemberjssandeep21:46 10 Sep '06  
GeneralRe: DataGridComboBox Working fine Pinmemberjssandeep22:03 10 Sep '06  
GeneralThis DataGridCombobox has errors Pinmemberjssandeep23:58 6 Sep '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 13 Sep 2006
Editor: Smitha Vijayan
Copyright 2004 by René Paw Christensen
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project