unbound DataGridView ComboBox

Marc Graham 21 Reputation points
2021-02-17T15:51:38.393+00:00

I have an unbound DataGridView. It has a combobox column. when I add a row to the DGV programmatically, the drop down list disappears from the combobox. The celltemplate has not changed in the Combobox column. If I try to set the value in the corresponding cell, I get a DataError ("formatting | preferred size").

How do I add rows to a DGV with a combobox column programmatically?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,099 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,016 Reputation points
    2021-02-17T17:36:33.917+00:00

    Hello,

    The following is has full source code. Originally written in VS2015 then opened and tested with minor mods in VS2019, .NET Framework 4.8

    69164-unbound.png

    Extension class

    using System.Windows.Forms;  
      
    namespace UnboundDataGridViewComboBox  
    {  
        public static class Extensions  
        {  
            public static bool IsComboBoxCell(this DataGridViewCell sender) =>   
                sender.EditType != null && sender.EditType == typeof(DataGridViewComboBoxEditingControl);  
        }  
    }  
    

    Form code

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Windows.Forms;  
      
    namespace UnboundDataGridViewComboBox  
    {  
        public partial class Form1 : Form  
        {  
            private AutoCompleteStringCollection _autoList =   
                new AutoCompleteStringCollection();  
              
            private ComboBox _cbo;  
            private string _comboColumnName = "C1";  
              
            public Form1()  
            {  
                InitializeComponent();  
                  
                DataGridView1.CellLeave += DataGridView1OnCellLeave;  
                DataGridView1.EditingControlShowing += DataGridView1OnEditingControlShowing;  
            }  
      
            private void DataGridView1OnEditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)  
            {  
                if (!DataGridView1.CurrentCell.IsComboBoxCell()) return;  
      
                if (DataGridView1.Columns[DataGridView1.CurrentCell.ColumnIndex].Name != _comboColumnName) return;  
                  
                _cbo = e.Control as ComboBox;  
                _cbo.DropDownStyle = ComboBoxStyle.DropDown;  
                _cbo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;  
                _cbo.AutoCompleteSource = AutoCompleteSource.ListItems;  
      
            }  
      
            private void DataGridView1OnCellLeave(object sender, DataGridViewCellEventArgs e)  
            {  
                if (_cbo == null) return;  
                if (string.IsNullOrWhiteSpace(_cbo.Text)) return;  
                  
                if (!_autoList.Contains(_cbo.Text))  
                {  
                    var cb = (DataGridViewComboBoxColumn)DataGridView1.Columns[0];  
                    _autoList.Add(_cbo.Text);  
                    var items = ((string[])cb.DataSource).ToList();  
                    items.Add(_cbo.Text);  
                    var index = items.FindIndex((x) => x.ToLower() == _cbo.Text.ToLower());  
                    cb.DataSource = items.ToArray();  
                    _cbo.SelectedIndex = index;  
                }  
      
            }  
      
            private void Form1_Load(object sender, EventArgs e)  
            {  
                var source = new[] { "Add", "Subtract", "Divide", "Multiply" };  
      
                var column1 = new DataGridViewComboBoxColumn  
                {  
                    DataSource = source,  
                    DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing,  
                    Name = _comboColumnName,  
                    HeaderText = "Demo",  
                    SortMode = DataGridViewColumnSortMode.NotSortable  
                };  
      
                var column2 = new DataGridViewCheckBoxColumn  
                {  
                    Name = "C2",  
                    HeaderText = "Col 2"  
                };  
                var column3 = new DataGridViewTextBoxColumn  
                {  
                    Name = "C3",  
                    HeaderText = "Col 3"  
                };  
      
                _autoList.AddRange(source);  
      
                DataGridView1.Columns.AddRange(column1, column2, column3);  
      
                DataGridView1.Rows.Add("Divide", true, "Karen");  
                DataGridView1.Rows.Add("Add", false, "Kevin");  
                DataGridView1.Rows.Add("Subtract", true, "Anne");  
                DataGridView1.Rows.Add("Add", true, "Joe");  
                DataGridView1.Rows.Add("Multiply", true, "Jean");  
      
    		}  
      
            private void AddNewRowButton_Click(object sender, EventArgs e)  
            {  
                DataGridView1.Rows.Add("Subtract", true, "Wendy");  
            }  
        }  
    }  
      
    
    0 comments No comments

  2. Daniel Zhang-MSFT 9,611 Reputation points
    2021-02-18T07:29:37.33+00:00

    Hi MarcGraham-7285,
    >>when I add a row to the DGV programmatically, the drop down list disappears from the combobox.
    How do you add a row to the DGV programmatically? Please provide your code to reproduce the situation.
    And you can also try the following code to add a ComboBox column to a DataGridView programmatically

    private void Form1_Load(object sender, EventArgs e)  
    {  
        DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();  
        cmb.Items.Add("AAAA");  
        cmb.Items.Add("BBBB");  
        cmb.Items.Add("CCCC");  
      
        dataGridView1.Rows.Add("1st Col", "2nd Col");  
        dataGridView1.Columns.Add(cmb);  
    }  
    

    Here is a related thread.
    Beside, you can also refer to Reza Aghaei'a code example.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments