locked
Problem with combobox and databound datagridview RRS feed

  • Question

  • Hi

    I have a datagridview that is databound to a table via a bindingsource and a DataGridViewComboBox column that is bound to a second table (both in the same dataset). I am dynamically adding the column to the grid. 

    Dim viewcol As New DataGridViewComboBoxColumnviewcol.DataSource = _dsEquivalents.Tables(1)
    viewcol.DataPropertyName =
    "ViewName"
    viewcol.ValueMember = "ViewTable"
    viewcol.DisplayMember = "ViewTable"
    viewcol.HeaderText = "View Name"
    viewcol.AutoComplete = False
    dgvEqu.Columns.Add(viewcol)

    BindingSource1.DataSource = m_dsEquivalents
    BindingSource1.DataMember = m_dsEquivalents.Tables(0).TableName


    The table bound to the grid contains values that are not in the table bound to the combo. This causes an Dataerror which I trap but the value still doesnt display in the grid. Do I need to do an ovverride? I would also like to be able to type values into the cell that are not in the combobox is this possible?
     

    Wednesday, May 25, 2005 10:20 AM

Answers

  • The DataGridView raises a DataError when the value is not in the ComboBox's list.  To display the value, you must add the value to the ComboBox.  The other option is to create your own combobox column.

    There must not be a foreign key relationship between your two tables, or else you wouldn't be having this problem.  How were you going to have users enter data not in the combobox?  It seems like you are looking for the ComboBoxStyle.DropDownList behaviour in DataGridViewComboBoxColumn.   What follows is an example of how to accomplish this.

    The ComboBox used by the DataGridViewComboBoxColumn has a DropDownStyle property set to ComboBoxStyle.DropDownList, but DataGridViewComboBoxColumn does not expose this property, so out-of-box there is no way to type text into a combobox column.  You can change this by handling the EditingControlShowing event, and setting the DropDownStyle:


    void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)

    {

    if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))

    {

    DataGridViewComboBoxEditingControl cbo = e.Control as DataGridViewComboBoxEditingControl;

    cbo.DropDownStyle = ComboBoxStyle.DropDown;

    cbo.Validating += new CancelEventHandler(cbo_Validating);

    }

    }


     



    In this example, all ComboBox columns will have the DropDownStyle property set to DropDown.  In addition, handle validating to add user-typed items to the list.



    void cbo_Validating(object sender, CancelEventArgs e)

    {

    DataGridViewComboBoxEditingControl cbo = sender as DataGridViewComboBoxEditingControl;

    DataGridView grid = cbo.EditingControlDataGridView;

    object value = cbo.Text;

    // Add value to list if not there

    if (cbo.Items.IndexOf(value) == -1)

    {

    DataGridViewComboBoxColumn cboCol = grid.Columns[grid.CurrentCell.ColumnIndex] as DataGridViewComboBoxColumn;

    // Must add to both the current combobox as well as the template, to avoid duplicate entries...

    cbo.Items.Add(value);

    cboCol.Items.Add(value);

    grid.CurrentCell.Value = value;

    }

    }


     

    Friday, May 27, 2005 5:24 PM

All replies

  • The DataGridView raises a DataError when the value is not in the ComboBox's list.  To display the value, you must add the value to the ComboBox.  The other option is to create your own combobox column.

    There must not be a foreign key relationship between your two tables, or else you wouldn't be having this problem.  How were you going to have users enter data not in the combobox?  It seems like you are looking for the ComboBoxStyle.DropDownList behaviour in DataGridViewComboBoxColumn.   What follows is an example of how to accomplish this.

    The ComboBox used by the DataGridViewComboBoxColumn has a DropDownStyle property set to ComboBoxStyle.DropDownList, but DataGridViewComboBoxColumn does not expose this property, so out-of-box there is no way to type text into a combobox column.  You can change this by handling the EditingControlShowing event, and setting the DropDownStyle:


    void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)

    {

    if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))

    {

    DataGridViewComboBoxEditingControl cbo = e.Control as DataGridViewComboBoxEditingControl;

    cbo.DropDownStyle = ComboBoxStyle.DropDown;

    cbo.Validating += new CancelEventHandler(cbo_Validating);

    }

    }


     



    In this example, all ComboBox columns will have the DropDownStyle property set to DropDown.  In addition, handle validating to add user-typed items to the list.



    void cbo_Validating(object sender, CancelEventArgs e)

    {

    DataGridViewComboBoxEditingControl cbo = sender as DataGridViewComboBoxEditingControl;

    DataGridView grid = cbo.EditingControlDataGridView;

    object value = cbo.Text;

    // Add value to list if not there

    if (cbo.Items.IndexOf(value) == -1)

    {

    DataGridViewComboBoxColumn cboCol = grid.Columns[grid.CurrentCell.ColumnIndex] as DataGridViewComboBoxColumn;

    // Must add to both the current combobox as well as the template, to avoid duplicate entries...

    cbo.Items.Add(value);

    cboCol.Items.Add(value);

    grid.CurrentCell.Value = value;

    }

    }


     

    Friday, May 27, 2005 5:24 PM
  • Hi Durstin,
                    In your post you said:
    >    "The other option is to create your own combobox column."

    Any chance you could give me a quick run through on how to do this? I presume it would mean inheriting from DataGridViewComboBoxColumn which in turn would mean inheriting from DataGridViewComboBoxCell in order to get access to the editing control. What method in
    DataGridViewComboBoxCell would I have to override in order to ensure any data which is not in the combo box's datasource is still drawn?

    I hope this makes sense!, if not I will try and explain it better.

    Thanks,
    Cathal.
    Thursday, June 9, 2005 3:42 PM
  • couple of things:

    1) seems that with every EditingControlShowing event an Additional handler is added and they build up.  Shouldn't the tail end of cbo_Validating have:
    cbo.Validating -= new CancelEventHandler(cbo_Validating);
    added so that cbo_Validating only executes once per EditingControlShowing event?
    when i add a trace to check the number of times cbo_Validating fires the number keeps getting higher ... maybe i implemented it different than you...

    2) intermittantly I'm still getting the data error.  not every time, but enough that I notice. And when I'm getting the error it seems that the data_error event is raised before the cbo.Validating event.  I'm starting to think about adding the item in .cellValidating as it executes before .DataError event

    what do you think?

    /gabe

    Friday, November 11, 2005 11:50 AM
  • hi,
    i have the same situation like in the first post. I tryed to bound the combobox via
    smart tag and manually in the formattingcell event. I bounded it to a dataset,datatable,dataview,arraylist. it always raises an dataerror.(wrong value)

    please give me an example how to bind the box to one column of my datatable.

    thanx
    Thursday, December 8, 2005 2:45 AM
  • http://www.windowsforms.net/Samples/Go%20To%20Market/DataGridView/DataGridView%20FAQ.doc

    seemed to answer the vast majority of the problems i had.  if that doesn't lead you to the solution repost and i'll put together a sample

    gabe
    Monday, December 12, 2005 8:08 AM
  • Thanks  again.
    Tuesday, December 13, 2005 7:07 AM
  • hi,

    in my program i have used one combobox . when i desing this combobox that time this is ok but now this combo is look transperent how it happened ? when i click on combo then it look like combo with item list but at first time when programe started it will like textbox with out border. i put another combo but it is like old one . this effect is show in this project only  if i working another project then combo is like good. if you say then i send you this splash screen with this combo.

    please give me solutional for this problem.

     

    raju

     

     

     

    Tuesday, June 20, 2006 6:51 AM
  • A thought for you Raju.

    Check to see if the DisplayStyle for the column is DropDownButton
    and the DisplayStyleForCurrentCellOnly is false.

    Tuesday, July 18, 2006 5:21 PM
  • I pieced together helpful code from this thread and other sources, translated them to VB.NET and enhanced it to work for ALL comboboxes in the DataGridView.  These routines should make the comboboxes editable, i.e., allow users to enter new values.  (I also included commented out code that limits it to a specific combobox.) 

    VB programmers should be able to copy and paste this code and just change "MyDataGridView" to the name of their DataGridView.  (If you uncomment the code that uses "MyDataGridViewComboBox", you will need to change that to the name of your combobox.)

    This assumes that the combobox list is not bound to a datasource, but filled in the Form_Load event.  This needs to be done for each combobox in the DataGridView.  Here is a sample:

    'TODO: This line of code loads data into the 'MyDataSet.MyList' table. You can move, or remove it, as needed.

    Me.MyTableAdapter.Fill(Me.MyDataSet.MyList)

    MyDataGridViewComboBox.Items.Clear()  'This probably isn't necessary if done in the Load.

    'fill combobox

    Dim row As DataRow

    For Each row In Me.MyDataSet.MyList

    MyDataGridViewComboBox.Items.Add(row.Item(0))

    Next

    VB programmers should be able to copy and paste the rest of this code and just change "MyDataGridView" to the name of their DataGridView.  (If you uncomment the code that uses "MyDataGridViewComboBox", you will need to change that to the name of your combobox.)

    Private Sub MyDataGridView_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles MyDataGridView.EditingControlShowing

    'Allow user to enter new values for ALL DataGridViewComboBox controls in the DataGridView

    If (TypeOf e.Control Is DataGridViewComboBoxEditingControl) Then

    Dim cmb As DataGridViewComboBoxEditingControl = CType(e.Control, DataGridViewComboBoxEditingControl)

    If Not cmb Is Nothing Then

    cmb.DropDownStyle = ComboBoxStyle.DropDown

    End If 

    End If

    'Following Works for a specific combobox ///////////

    'If MyDataGridView.CurrentCellAddress.X = MyDataGridViewComboBox.DisplayIndex Then

    ' Dim cmb As ComboBox = CType(e.Control, ComboBox)

    ' If Not cmb Is Nothing Then

    ' cmb.DropDownStyle = ComboBoxStyle.DropDown

    ' End If

    'End If

    End Sub

     

    Private Sub MyDataGridView_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles MyDataGridView.CellValidating

    'Allow user to enter new values for all DataGridViewComboBox controls in the DataGridView

    If (TypeOf CType(sender, DataGridView).EditingControl Is DataGridViewComboBoxEditingControl) Then

    Dim cmb As DataGridViewComboBoxEditingControl = CType(CType(sender, DataGridView).EditingControl, DataGridViewComboBoxEditingControl)

    If Not cmb Is Nothing Then

    Dim grid As DataGridView = cmb.EditingControlDataGridView

    Dim value As Object = cmb.Text

    '// Add value to list if not there

    If cmb.Items.IndexOf(value) = -1 Then

    '// Must add to both the current combobox as well as the template, to avoid duplicate entries...

    cmb.Items.Add(value)

    Dim cmbCol As DataGridViewComboBoxColumn = CType(grid.Columns(grid.CurrentCell.ColumnIndex), DataGridViewComboBoxColumn)

    If Not cmbCol Is Nothing Then

    cmbCol.Items.Add(value)

    End If

    End If

    grid.CurrentCell.Value = value

    End If

    End If

    ''Following Works for a specific combobox ///////////

    'If e.ColumnIndex = MyDataGridView.Columns("DataGridViewComboBoxColSize").Index Then 'CType(sender, DataGridView).CurrentCell.ColumnIndex

    ' 'Dim cmb As ComboBox = CType(e.Control, ComboBox)

    ' Dim cmb As DataGridViewComboBoxEditingControl = CType(CType(sender, DataGridView).EditingControl, DataGridViewComboBoxEditingControl)

    ' If Not cmb Is Nothing Then

    ' Dim grid As DataGridView = cmb.EditingControlDataGridView

    ' Dim value As Object = cmb.Text

    ' '// Add value to list if not there

    ' If cmb.Items.IndexOf(value) = -1 Then

    ' '// Must add to both the current combobox as well as the template, to avoid duplicate entries...

    ' cmb.Items.Add(value)

    ' Dim cmbCol As DataGridViewComboBoxColumn = CType(grid.Columns(grid.CurrentCell.ColumnIndex), DataGridViewComboBoxColumn)

    ' If Not cmbCol Is Nothing Then

    ' cmbCol.Items.Add(value)

    ' End If

    ' grid.CurrentCell.Value = value

    ' End If

    ' End If

    'End If

    ''//////////

    End Sub

     

    Private Sub MyDataGridView_DataError(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles MyDataGridView.DataError

    'I don't know if this is really necessary.

    If e.Exception.Message = "DataGridViewComboBoxCell value is not valid." Then

    e.Cancel = True

    End If

    End Sub

    Wednesday, August 16, 2006 10:44 PM
  • My reply is to the origianl post and also that which explians the cause of the error as a value not in the list of items in the combobox column.

    First I have the same problem as originally stated. I'm convinced that the combobox column property DataPropertyName is not set to something valid - in fact the DataSource for the box seems to supply info from only one table - it is after set to a single DataTable object.

    As for values not being in the dropdownlist, I agree its a problem, but in a parent/chaild table, the re will be FK's in the parent table that are NULL. This should not cause an error. It certainly doesn't in the normal Combobox control. I have both on a single form and the normal combobox works fine from the same two tables all because it can be bound to both tables through data bindings. The combobox column doesn't have that ability.
    Friday, October 6, 2006 5:46 PM
  • Hi,

    I have copied this code but I get this error:

    "No se puede modificar la colección Items cuando está establecida la propiedad DataSource."

    in

    cmb.Items.Add(value)

    I fill the comboboxcolumn from a database and I belive that this is the problem. How can I solve it?


    Thanks
    Sunday, October 22, 2006 6:16 PM
  • First, I can't read much else but English, so I don't understand your question.

    Second...In many other posts of mine and others' its become clear that the DataGridView Combobox control is incomplete. It needs the capability to bind to two tables in a dataset. The normal combobox control has this ability through its databinding collection. The current DGV Combobox gives all of us roughly the same errors for very much the same reasons.
    Monday, October 23, 2006 6:45 PM
  • Hi mafc,

    I'm guessing your problem is you have bound the DataSource property.  Instead, set DataSource to "none" and fill the combo's Items collection in the Form_Load event.  Here is sample code from my previous post in this thread to do this:

    Me.MyTableAdapter.Fill(Me.MyDataSet.MyList)

    MyDataGridViewComboBox.Items.Clear()  'This probably isn't necessary if done in the Load.

    'fill combobox

    Dim row As DataRow

    For Each row In Me.MyDataSet.MyList

    MyDataGridViewComboBox.Items.Add(row.Item(0))

    Next

    Hope that helps!

    Monday, October 23, 2006 8:26 PM

  • Yes this is my problem, but I don't know how to use your example in my code.  My code is this :

                dim column_combo As DataGridViewComboBoxColumn = New DataGridViewComboBoxColumn()
           .....

                SQL = "select CANT_NOMBRE from T_CANTIDADES"

                Dim dbDataSet_Cantidades As New Data.DataSet
                Dim tabla_Cantidades As New DataTable

                Try
                    dbDataSet_Cantidades.Clear()

                    dbDataAdapter = New FirebirdSql.Data.FirebirdClient.FbDataAdapter(SQL, FbConnection)
                    dbDataAdapter.Fill(dbDataSet_Cantidades)

                    tabla_Cantidades = dbDataSet_Cantidades.Tables(0)

                Catch ex As Exception ' catches any error

                    MsgBox("Ha fallado al rellenar la columna cantidad")
                Finally
                End Try

                With column_combo

                    .DataSource = tabla_Cantidades
                    .ValueMember = "CANT_NOMBRE"
                    .DisplayMember = .ValueMember
                    .......
                    .DataPropertyName = "CANTIDAD"
                    .HeaderText = "CANTIDAD"
                    .HeaderCell.Value = "CANTIDAD"

                End With

                Me.DGV_Recetas.Columns.Add(column_combo)

    Can I incorporate your code in the mine.

    Thanks


    Wednesday, October 25, 2006 9:31 PM
  •  

     Hi mafc,

    Try this code (notice I took out ".DataSource = tabla_Cantidades" and replaced it with filling the items collection):

                dim column_combo As DataGridViewComboBoxColumn = New DataGridViewComboBoxColumn()
           .....

                SQL = "select CANT_NOMBRE from T_CANTIDADES"

                Dim dbDataSet_Cantidades As New Data.DataSet 

                Try
                    dbDataSet_Cantidades.Clear()

                    dbDataAdapter = New FirebirdSql.Data.FirebirdClient.FbDataAdapter(SQL, FbConnection)
                    dbDataAdapter.Fill(dbDataSet_Cantidades)

                Catch ex As Exception ' catches any error

                    MsgBox("Ha fallado al rellenar la columna cantidad")
                Finally
                End Try

                With column_combo

                 Dim row As DataRow

                     For Each row In dbDataSet_Cantidades

                           .Items.Add(row.Item(0))

                     Next

                    .......
                    .DataPropertyName = "CANTIDAD"
                    .HeaderText = "CANTIDAD"
                    .HeaderCell.Value = "CANTIDAD"

                End With

                Me.DGV_Recetas.Columns.Add(column_combo)


    Thursday, October 26, 2006 4:12 AM
  • Thank you mcassoc for your help. I have followed your advice and It works with a little change. I have marked in red.

    Dim row As DataRow
    For Each row In tabla_Cantidades.Select
    .Items.Add(row.Item(0))
    Next


    Now, I can edit the comboboxcolumn but the value that I write in the combobox disapper when I change to other cell. Which is the problem?

    Thanks


    Thursday, October 26, 2006 10:15 PM
  • Hi mafc,

    Glad to help.  I know it took me quite awhile to figure this out and I appreciated help from others.

    Here are some questions to try to narrow down the problem:

    Do you have my code from my 8/16/06 post in these three subs?

    DGV_Recetas_EditingControlShowing

    DGV_Recetas_CellValidating

    DGV_Recetas_DataError

    Is the datatype the same for your "CANTIDAD" field that you use for the DataPropertyName and the "CANT_NOMBRE" in the T_CANTIDADES table?

    Do other fields in the grid get saved properly?

    Is the value you typed getting added to the dropdown list?

    Friday, October 27, 2006 5:21 PM
  • Hi all,

      My case is like this, I have a DataGridView where the first column is a combo box, the items in the combo box are added from a dictionary

    foreach (KeyValuePair<string, long> key in dictionary)
    {
        tmpCol.Items.Add(key.Key);
    }

    This code is in the constructor of the form, and I have done everything as stated by durstin and mcassoc, I can now edit the combo box etc.

    But now i have two problems:
    1. After I selected an item and lose the focus of the cell, i got back to the combo box, the items in the combo box are doubled....

    say like i have A, B, C in the combo box and I chose B, lose the control and i go back, the combo box will have A, B, C, A, B, C... I didn't implement to add the items to code else where but in the constructor only, any clue how could this happen?

    2. I also have the same problem as mafc, I can edit the comboboxcolumn but the value that I write in the combobox disapper when I change to other cell, I solve this by implementing CellLeave event, I cleared the items in the comboboxcolumn and I add the items from the dictionary back into it again, and then

    DataGridView.CurrentCell.Value = theTextWasTypedInByTheUser;

    this is ok if I have few items, but if I have many items it will be very slow, any one has a clue on how to solve this also?

    I am quite new to this stuff, Thank you very much
    Sunday, October 29, 2006 10:56 AM

  • As you said to me the datatypes aren't equal. "CANTIDAD" is INTERGER and CANT_NOMBRE is VARCHAR.

    I have a column "CANTIDAD" that it will a number column (100, 500,...), but in the combo I want to have a varchar code (¼,½,¾). I want to give the oportunity of put ½ instead of 500. Is this posible?

    Thanks


    Sunday, October 29, 2006 11:32 PM

  • I change the sql and I have the same type in both. The two are integer and I have the same problem.


    Tuesday, October 31, 2006 10:30 PM
  • I used mcassoc's code from the previous page converted to C# and have it working except for one very annoying problem.  I go through the cells editing the values, but then if I go back to a cell and click on it, it goes into edit mode as expected with all of the text selected, but if I click the down arrow, the dropdown opens, then immediately closes.  No matter what I do, I cannot get the dropdown to stay open.

    I can still edit the value in the cell by typing in a new value or by using the cursor keys to scroll through available values, but the dropdown doesn't work.

    Does anybody else have this problem or have any idea what I might have done wrong?  I have been trying everything I can think of, so any help would really be appreciated.  Thanks.
    Tuesday, January 16, 2007 3:55 AM
  • Rob,

    I'm sorry I don't have a solution for you.  I don't have that problem in my VB forms.

    mcassoc

    Tuesday, January 16, 2007 12:10 PM
  • mafc,

    Text will not display in the cell after you leave it if it has not been added to the combobox dropdown list properly.  Please see my code in MyDataGridView_CellValidating in my 8/16/06 post to see how to do this.

    I'm sorry I didn't respond months ago.  Hopefully, you figured it out.

    mcassoc

    Tuesday, January 16, 2007 12:33 PM
  • Paul,

    As I mentioned in my post  to mafc, text will not display in the cell after you leave it if it has not been added to the combobox dropdown list properly.  Please see my code in MyDataGridView_CellValidating in my 8/16/06 post to see how to do this.  Make sure you are adding new values to the current combobox and the template.  This will help prevent some duplicates, but I don't understand why your entire list is getting duplicated if the only "Add" code is in the constructor of the form (and individual items that the user adds in CellValidating). 

    I'm sorry I didn't respond months ago.  Hopefully, you figured it out.

    mcassoc

    Tuesday, January 16, 2007 12:54 PM
  • I pieced together helpful code from this thread and other sources, translated them to VB.NET and enhanced it to work for ALL comboboxes in the DataGridView.  These routines should make the comboboxes editable, i.e., allow users to enter new values.  (I also included commented out code that limits it to a specific combobox.) 
    VB programmers should be able to copy and paste this code and just change "MyDataGridView" to the name of their DataGridView.  (If you uncomment the code that uses "MyDataGridViewComboBox", you will need to change that to the name of your combobox.)
    This assumes that the combobox list is not bound to a datasource, but filled in the Form_Load event.  This needs to be done for each combobox in the DataGridView.  Here is a sample:
    'TODO: This line of code loads data into the 'MyDataSet.MyList' table. You can move, or remove it, as needed.
    Me.MyTableAdapter.Fill(Me.MyDataSet.MyList)
    MyDataGridViewComboBox.Items.Clear()  'This probably isn't necessary if done in the Load.
    'fill combobox
    Dim row As DataRow
    For Each row In Me.MyDataSet.MyList
    MyDataGridViewComboBox.Items.Add(row.Item(0))
    Next
    VB programmers should be able to copy and paste the rest of this code and just change "MyDataGridView" to the name of their DataGridView.  (If you uncomment the code that uses "MyDataGridViewComboBox", you will need to change that to the name of your combobox.)
    Private Sub MyDataGridView_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles MyDataGridView.EditingControlShowing
    'Allow user to enter new values for ALL DataGridViewComboBox controls in the DataGridView
    If (TypeOf e.Control Is DataGridViewComboBoxEditingControl) Then
    Dim cmb As DataGridViewComboBoxEditingControl = CType(e.Control, DataGridViewComboBoxEditingControl)
    If Not cmb Is Nothing Then
    cmb.DropDownStyle = ComboBoxStyle.DropDown
    End If 
    End If
    'Following Works for a specific combobox ///////////
    'If MyDataGridView.CurrentCellAddress.X = MyDataGridViewComboBox.DisplayIndex Then
    ' Dim cmb As ComboBox = CType(e.Control, ComboBox)
    ' If Not cmb Is Nothing Then
    ' cmb.DropDownStyle = ComboBoxStyle.DropDown
    ' End If
    'End If
    End Sub
     
    Private Sub MyDataGridView_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles MyDataGridView.CellValidating
    'Allow user to enter new values for all DataGridViewComboBox controls in the DataGridView
    If (TypeOf CType(sender, DataGridView).EditingControl Is DataGridViewComboBoxEditingControl) Then
    Dim cmb As DataGridViewComboBoxEditingControl = CType(CType(sender, DataGridView).EditingControl, DataGridViewComboBoxEditingControl)
    If Not cmb Is Nothing Then
    Dim grid As DataGridView = cmb.EditingControlDataGridView
    Dim value As Object = cmb.Text
    '// Add value to list if not there
    If cmb.Items.IndexOf(value) = -1 Then
    '// Must add to both the current combobox as well as the template, to avoid duplicate entries...
    cmb.Items.Add(value)
    Dim cmbCol As DataGridViewComboBoxColumn = CType(grid.Columns(grid.CurrentCell.ColumnIndex), DataGridViewComboBoxColumn)
    If Not cmbCol Is Nothing Then
    cmbCol.Items.Add(value)
    End If
    End If
    grid.CurrentCell.Value = value
    End If
    End If
     
    ''Following Works for a specific combobox ///////////
    'If e.ColumnIndex = MyDataGridView.Columns("DataGridViewComboBoxColSize").Index Then 'CType(sender, DataGridView).CurrentCell.ColumnIndex
    ' 'Dim cmb As ComboBox = CType(e.Control, ComboBox)
    ' Dim cmb As DataGridViewComboBoxEditingControl = CType(CType(sender, DataGridView).EditingControl, DataGridViewComboBoxEditingControl)
    ' If Not cmb Is Nothing Then
    ' Dim grid As DataGridView = cmb.EditingControlDataGridView
    ' Dim value As Object = cmb.Text
    ' '// Add value to list if not there
    ' If cmb.Items.IndexOf(value) = -1 Then
    ' '// Must add to both the current combobox as well as the template, to avoid duplicate entries...
    ' cmb.Items.Add(value)
    ' Dim cmbCol As DataGridViewComboBoxColumn = CType(grid.Columns(grid.CurrentCell.ColumnIndex), DataGridViewComboBoxColumn)
    ' If Not cmbCol Is Nothing Then
    ' cmbCol.Items.Add(value)
    ' End If
    ' grid.CurrentCell.Value = value
    ' End If
    ' End If
    'End If
    ''//////////
     
     
    End Sub
     
     
    Private Sub MyDataGridView_DataError(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles MyDataGridView.DataError
    'I don't know if this is really necessary.
    If e.Exception.Message = "DataGridViewComboBoxCell value is not valid." Then
    e.Cancel = True
    End If
    End Sub
     

     

    Hi mcassoc

        The code was very very useful. I have some nitty-gritties

                      1. When I start typing in the combobox the dropdown has to be switched on and autocomplete has to be switched on.

                      2.  And when I press on ENTER that particular data that data has to get selected and move the cursor to the next column not next row 

                      3. Normally I need my cursor to be switched from one column to another when I press ENTER and as well as TAB key

     

    Any great Idea are welcome

     Parameswaran.N

     

    Monday, February 5, 2007 2:39 PM
  • hey it works..

    It saved me a lot of time...

    Friday, April 13, 2007 12:46 PM
  •  

    the code helped me a lot. Thanks

     

    But say I want to validate the data while entering the data inthe combo box...like in general we do it in datagrid_keydown..

     

    (Req:I want to validata whether the entered data is number or not..is number only I would like to enter the value in the combo box)

     

    But I couldn't get how to assign the validation on the key down on that particular combobox (which I set it as drop down style)

     

    plz help me

    Saturday, May 19, 2007 6:19 AM
  • Please also keep in mind to set the ValueType of your column or you might get DataErrors and in case of use a ComboColumn your selection list may not display correctly.

     

    Kind regards

    Tom

    Friday, July 6, 2007 6:16 AM
  • Thanks for the nice piece of code and advice.

     

    I have just a small little problem.. How do I invoke the DataGridView_DataError events handler?

     

    My situation is ..

     

    I having a combobox and bind it to show data from another table. Basically it's just a list of "item no." field values. Since the user might use the barcode reader. So I have to do some filteration on the code retrieved in from the barcode reader before searching the list in the combo box. If the "item no." value is not there in the list, I want to throw an exception telling the user that the "item no." input is invalid and check on it.

     

     

    Thank you in advance for any helps..

     

    Regards,

    Weoi Li

    Wednesday, July 18, 2007 9:46 AM
  •  

    Hi

    I have a situation where in I have two combo boxes in a datagridview control. The first combo box items are all static. But the second combo box items need to change based on the first combo box value selected. The problem I am running into is if I bind the datasource to the column the values are all the same all the time and i couldn't see the second combobox values when i select first combobox.

     

    Please help me

     

    Thanks in Advance,

     

    Gangadhar

    Friday, July 20, 2007 11:20 AM
  • Hi,

    Here is an example using BindingSource Object...

        Private Sub editingComboBox_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
            Dim cbo As DataGridViewComboBoxEditingControl = CType(sender, DataGridViewComboBoxEditingControl)
            Dim grid As DataGridView = cbo.EditingControlDataGridView
            Dim value As Object = cbo.Text

            If cbo.Items.IndexOf(value) = -1 Then
                Dim cboCol As DataGridViewComboBoxColumn = CType(grid.Columns(grid.CurrentCell.ColumnIndex), DataGridViewComboBoxColumn)

                ' Create a new row for the DataTable member
                Dim dr As DataRow = Me.m_ds.Tables(0).NewRow()
                dr("ComboboxField") = value

                ' Add row to the datatable
                Me.m_ds.Tables(0).Rows.Add(dr)

                ' Change the current property of the binding source object
                bndComboBox.MoveLast()

                grid.CurrentCell.Value = value
            End If
        End Sub


    I'm not completely sure why the bindingsources's current / position property needs to be set.  I thought by setting the grid.CurrentCell.Value that this would be taken care of, but it was not.  Anyone have some insight on this bit of trivia?

    Thanks for all everyone's help

    Peter
    Friday, June 19, 2009 6:53 PM
  • Hy Guys

    I also have a problem with a combobox in a datagridview. Here is my code:

     

    Dim cmd As OleDbCommand = New OleDbCommand("Select AnneDbut, CycleDbut,AnneFin, CycleFin, Quantit, Dims,Client From TTable", con)

     

    Dim cmd2 As OleDbCommand = New OleDbCommand("Select AllDimensions From Dimensions", con)

    con.Open()

    myDA =

    New OleDbDataAdapter(cmd)

    myDA2 =

    New OleDbDataAdapter(cmd2)

    builder =

    New OleDbCommandBuilder(myDA)

    builder.QuotePrefix =

    "["

    builder.QuoteSuffix =

    "]"

     

    myDataSet =

    New DataSet()

    myDA.Fill(myDataSet,

    "MyTable")

    DataGridView1.AutoGenerateColumns =

    True

    myDataSet2 =

    New DataSet()

    myDA2.Fill(myDataSet2,

    "MyDim")

     

    Dim comboboxColumn As New DataGridViewComboBoxColumn

    comboboxColumn.DataSource = myDataSet2.Tables(

    "MyDim").DefaultView  'Here i fill the combobox with the content of the table DIMENSIONS

    comboboxColumn.DisplayMember =

    "AllDimensions"

    comboboxColumn.ValueMember =

    "AllDimensions"

    comboboxColumn.Name =

    "Selected Dimensions"

    comboboxColumn.DataPropertyName =

    "Dims"

    DataGridView1.DataSource = myDataSet.Tables(

    "MyTable").DefaultView  'I fill the datagridview with the content of TTable

    DataGridView1.Columns.Insert(5, comboboxColumn) 'I insert a column containing the combobox

    con.Close()

    con =

    Nothing

     

    Catch ex As Exception

    MessageBox.Show(ex.Message)

     

    End Try

    My goal is  when i start the application, the datagridview will be filled with the content of the table TTable and the combobox should show the value of the column Dims of my TTable and when i click on the combobox column, it would allow me to change the value of the cell. My problem is that I cannot find the way to dispaly the content of the Dims column of my TTable.

    Where am I wrong in my code? Could you please help me?

    Thanks

    Tuesday, July 13, 2010 8:20 AM
  • Thanks you.... it work for me
    Friday, January 26, 2018 11:59 PM