locked
Problem with value DataGridViewComboBoxCell RRS feed

  • Question

  • In VB 2005 Express I have a problem, which completely do not understand. I use a DataGridViewComboBox in a DataGridView. When I change data and save it, I have no problem. But when I close the form I a repeting error, being: System.ArgumentException: DataGridViewComboBoxCell value is not valid.

    Can anybody help?

    Thanks in advance,
    Simon
    Tuesday, November 15, 2005 9:14 PM

Answers

  • Thanks for the suggestion.
    I have solved it by deleting the DGV and created a new one, with the same combobox. Since then I didn't have the issue anymore.
    Tuesday, November 22, 2005 10:35 PM

All replies

  • Does the data you saved exist in the DataGridViewComboBoxCell's items list?

    For instance, if your DataGridViewComboBoxCell::Items collection is {"one", "two", "three" } and the value you saved is "four" then you will get this error.

    Another situation is if your DataGridViewComboBoxCell is data bound. For example sake, say that the ComboBox displays data from a DataTable, say it displays data from the DataColumn "Number".  If the DataColumn contains  "one", "two", and "three" and the value you saved is "four" then you will also get this error.

    Hope this helps,
    Daniel.

    • Proposed as answer by sairenji Wednesday, May 6, 2009 1:50 AM
    Tuesday, November 15, 2005 9:34 PM
  • Yes, the save works fine and also actually saves.

    My data is coming from a table and the display member and value member are different fields.

    But now it has become even more strange. I don't know what I changed, but the error is gone. So for now I'm OK, but when it happens again, I don't know how to solve this.

    Regards,
    Simon
    • Proposed as answer by rootyosi Tuesday, June 21, 2011 12:44 AM
    Wednesday, November 16, 2005 9:23 AM
  • And the problem is back again. I have changed nothing to that field. I was making some other changes to the form and then the problem was there and disappeared again. But also surfaced again. I realy don't understand this.

    Any suggestions?

    Regards,
    Simon
    Wednesday, November 16, 2005 5:52 PM
  • So the combobox's items contain the value that you save -  see my previous post?

    If you have a sample app can you post it here? Also, can you post what value you save the combobox to?

    Thanks,
    Daniel.
    Friday, November 18, 2005 1:12 AM
  • I have the same problem and it is becoming a little frustrating. I have not even changed anything on the particular form that is throwing the error.
    Tuesday, November 22, 2005 8:00 PM
  • I found a work around. If I take out the databindings for the grid before closing the form I don't get the error.



    Me
    .dgvStoreVisit.DataSource = Nothing
    Me.Close()

     


    • Proposed as answer by ali nouman Saturday, February 11, 2012 9:04 PM
    Tuesday, November 22, 2005 8:08 PM
  • Thanks for the suggestion.
    I have solved it by deleting the DGV and created a new one, with the same combobox. Since then I didn't have the issue anymore.
    Tuesday, November 22, 2005 10:35 PM
  • I have now found what caused the issue. When I turn the autosizemode for a DataGridViewComboBoxColumn on, I will get the error. When I turn it off, I have no problem.

    Regards,
    Simon
    Tuesday, November 29, 2005 11:33 PM
  • If you autosize the column but have not provided the combo box column with a valid datasource or you haven't yet added items to the combo box column's items collection then you'll get this error at startup because autosizing requires the cell's FormattedValue to be requested. Requesting the FormattedValue of a combo box cell is where the check is done that may raise the data error exception you are seeing.

    Set the autosize mode after you fill the combo box and things should be ok.

    -mark
    DataGridView Program Manager
    Microsoft
    This post is provided "as-is"
    Wednesday, November 30, 2005 1:57 AM
  • Mark,

    That sounds resonable. But I receive the error while closing the form.

    Simon
    Wednesday, November 30, 2005 10:59 PM
  • Right now I'd say that you'll want to remove the autosizing in the grid's dispose event or in the form's closing event.

     

    Can you file a bug for this? This will help us identify what is going on here.

     

    thanks,

    -mark
    DataGridView Program Manager
    Microsoft
    This post is provided "as-is"

     

    Wednesday, November 30, 2005 11:44 PM
  • Mark,

    Thanks for the workaround.

    I don't mind filing a bug, but where can I do that. When VBE was still beta there where some links to bugs and suggestion forums, but I can't find those anymore.

    Regards,
    Simon
    Thursday, December 1, 2005 8:17 AM
  • Use the following link: http://lab.msdn.microsoft.com/productfeedback/Default.aspx

     

    -mark

    DataGridView Program Manager
    Microsoft
    This post is provided "as-is"

     

    Thursday, December 1, 2005 3:41 PM
  • Done
    Friday, December 2, 2005 9:18 AM
  • I have the same problem but the workaround with Autosize on DataGridComboBox does not work for me.

    My scenario:
    I have a treeview to the left and a datagridview to the left and depending on the type of node the user select I display different data (and different DataGridComboBox). The error displays when changing nodes in the tree. It always works the first on first select (regardless of node) but when selecting different nodes I get errormess.
    Have tried disabling all autosizing on columns and grid, datasource = null but no luck...
    Monday, December 5, 2005 7:34 AM
  • The Microsoft bug site is saying they can't reproduct the bug!

    I'm now getting the same error without having the autosize turned on. I've verified that every value in the data source for the grid exists in the DataGridViewComboBoxColumn data source. Also if I unbind the DataGridViewComboBoxColumn box but leave it's datasource property set, the list displays correctly with the right values in it. However when I set the DataPropertyName I get the System.FormatException.
    Tuesday, December 6, 2005 6:08 PM
  • I had this problem too. Data for the combo box came from a SQL database. Worked fine until I changed the underlying schema for unrelated columns. Fixed by turning off autosizing of columns, as Simon has noted.
    Wednesday, December 14, 2005 5:26 AM
  • I found another work around

    i created my own

    DataGridViewComboBoxCell  by inherting from the original one and overrided:

    protected override object GetFormattedValue(object value, int rowIndex, ref System.Windows.Forms.DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter valueTypeConverter, System.ComponentModel.TypeConverter formattedValueTypeConverter, System.Windows.Forms.DataGridViewDataErrorContexts context)

    {

    return value.ToString();

    }

     

    the grid works perfictly now.

     

    i convinsed the column to create my own cells by stecifying

    _column.CellTemplate = new ComboBoxControlForRow.myComboBoxCell();

    • Proposed as answer by R. Offereins Friday, March 12, 2010 10:45 AM
    Sunday, December 18, 2005 12:43 PM
  • Mark,

    I am having the same problem.  My work around is:

    private void DataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)

    {

    if (e.Context == (DataGridViewDataErrorContexts.Formatting | DataGridViewDataErrorContexts.PreferredSize))

    {

    e.ThrowException = false;

    }

    }

    Jerry...

    Monday, December 19, 2005 7:54 AM
  • The error occurs during Dispose.
    It only occurs when the width of the row is wider than the width of the DGV client area.
    The colum size is always 0,0 for some strange reason.  It's a proper size on the display.
    The DataGridViewComboBox colums get cleared, row by row, at least three times during Dispose.
    The event {System.Windows.Forms.DataGridViewDataErrorEventArgs} gets thrown every time a cell clears.
    The view is still populated.
    The cell does have the proper value in it.
    The DataGridViewComboBox.DataSource is "null".  It looks like the DataSource is getting cleared *before* it should.

    Jerry...

    ColumnIndex 1 = DataGridViewComboBox
    RowIndex = 0

    DataGridView.Rows[0].Cells[1].Height = 0
    DataGridView.Rows[0].Cells[1].Width = 0

    ///// dgvCollection Properties /////
    -  dgvCollection {System.Windows.Forms.DataGridView} System.Windows.Forms.DataGridView
    +  base {System.Windows.Forms.DataGridView} System.Windows.Forms.Control {System.Windows.Forms.DataGridView}
    +  AdjustedTopLeftHeaderBorderStyle {DataGridViewAdvancedBorderStyle { All=NotSet, Left=OutsetDouble, Right=Outset, Top=OutsetDouble, Bottom=Outset }} System.Windows.Forms.DataGridViewAdvancedBorderStyle
    +  AdvancedCellBorderStyle {DataGridViewAdvancedBorderStyle { All=Single, Left=Single, Right=Single, Top=Single, Bottom=Single }} System.Windows.Forms.DataGridViewAdvancedBorderStyle
    +  AdvancedColumnHeadersBorderStyle {DataGridViewAdvancedBorderStyle { All=OutsetPartial, Left=OutsetPartial, Right=OutsetPartial, Top=OutsetPartial, Bottom=OutsetPartial }} System.Windows.Forms.DataGridViewAdvancedBorderStyle
    +  AdvancedRowHeadersBorderStyle {DataGridViewAdvancedBorderStyle { All=OutsetPartial, Left=OutsetPartial, Right=OutsetPartial, Top=OutsetPartial, Bottom=OutsetPartial }} System.Windows.Forms.DataGridViewAdvancedBorderStyle
      AllowUserToAddRows true bool
      AllowUserToDeleteRows true bool
      AllowUserToOrderColumns false bool
      AllowUserToResizeColumns true bool
      AllowUserToResizeRows true bool
    +  AlternatingRowsDefaultCellStyle {DataGridViewCellStyle { }} System.Windows.Forms.DataGridViewCellStyle
      AutoGenerateColumns false bool
      AutoSize false bool
      AutoSizeColumnsMode None System.Windows.Forms.DataGridViewAutoSizeColumnsMode
      AutoSizeRowsMode DisplayedCells System.Windows.Forms.DataGridViewAutoSizeRowsMode
    +  BackColor "{Name=Control, ARGB=(255, 236, 233, 216)}" System.Drawing.Color
    +  BackgroundColor "{Name=AppWorkspace, ARGB=(255, 128, 128, 128)}" System.Drawing.Color
      BackgroundImage null System.Drawing.Image
      BackgroundImageLayout Tile System.Windows.Forms.ImageLayout
      BorderStyle FixedSingle System.Windows.Forms.BorderStyle
      CellBorderStyle Single System.Windows.Forms.DataGridViewCellBorderStyle
      ClipboardCopyMode EnableWithAutoHeaderText System.Windows.Forms.DataGridViewClipboardCopyMode
      ColumnCount 4 int
      ColumnHeadersBorderStyle Raised System.Windows.Forms.DataGridViewHeaderBorderStyle
    +  ColumnHeadersDefaultCellStyle {DataGridViewCellStyle { BackColor=Color [Control], ForeColor=Color [WindowText], SelectionBackColor=Color [Highlight], SelectionForeColor=Color [HighlightText], Font=[Font: Name=Microsoft Sans Serif, Size=8.25, Units=3, GdiCharSet=0, GdiVerticalFont=False], WrapMode=True, Alignment=MiddleLeft }} System.Windows.Forms.DataGridViewCellStyle
      ColumnHeadersHeight 23 int
      ColumnHeadersHeightSizeMode EnableResizing System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode
      ColumnHeadersVisible true bool
    +  Columns {System.Windows.Forms.DataGridViewColumnCollection} System.Windows.Forms.DataGridViewColumnCollection
    +  CurrentCell {DataGridViewTextBoxCell { ColumnIndex=0, RowIndex=0 }} System.Windows.Forms.DataGridViewCell {System.Windows.Forms.DataGridViewTextBoxCell}
    +  CurrentCellAddress {X = 0 Y = 0} System.Drawing.Point
    +  CurrentRow {DataGridViewRow { Index=0 }} System.Windows.Forms.DataGridViewRow
      DataMember "" string
    +  DataSource { [System.Windows.Forms.BindingSource]} object {System.Windows.Forms.BindingSource}
    +  DefaultCellStyle {DataGridViewCellStyle { BackColor=Color [Window], ForeColor=Color [ControlText], SelectionBackColor=Color [Highlight], SelectionForeColor=Color [HighlightText], Font=[Font: Name=Microsoft Sans Serif, Size=8.25, Units=3, GdiCharSet=0, GdiVerticalFont=False], WrapMode=False, Alignment=MiddleLeft }} System.Windows.Forms.DataGridViewCellStyle
    +  DisplayRectangle {X = 0 Y = 0 Width = 641 Height = 422} System.Drawing.Rectangle
    +  EditingControl null System.Windows.Forms.Control
    +  EditingPanel {System.Windows.Forms.Panel, BorderStyle: System.Windows.Forms.BorderStyle.None} System.Windows.Forms.Panel
      EditMode EditOnKeystrokeOrF2 System.Windows.Forms.DataGridViewEditMode
      EnableHeadersVisualStyles true bool
    +  FirstDisplayedCell {DataGridViewTextBoxCell { ColumnIndex=0, RowIndex=0 }} System.Windows.Forms.DataGridViewCell {System.Windows.Forms.DataGridViewTextBoxCell}
      FirstDisplayedScrollingColumnHiddenWidth 0 int
      FirstDisplayedScrollingColumnIndex 0 int
      FirstDisplayedScrollingRowIndex 0 int
    +  Font {Name = "Microsoft Sans Serif" Size=8.25} System.Drawing.Font
    +  ForeColor "{Name=ControlText, ARGB=(255, 0, 0, 0)}" System.Drawing.Color
    +  GridColor "{Name=ControlDark, ARGB=(255, 172, 168, 153)}" System.Drawing.Color
      HorizontalScrollingOffset 0 int
      IsCurrentCellDirty false bool
      IsCurrentCellInEditMode false bool
      IsCurrentRowDirty false bool
      MultiSelect true bool
      NewRowIndex 3 int
    +  Padding {Left=0,Top=0,Right=0,Bottom=0} System.Windows.Forms.Padding
      ReadOnly false bool
      RowCount 4 int
      RowHeadersBorderStyle Raised System.Windows.Forms.DataGridViewHeaderBorderStyle
    +  RowHeadersDefaultCellStyle {DataGridViewCellStyle { BackColor=Color [Control], ForeColor=Color [WindowText], SelectionBackColor=Color [Highlight], SelectionForeColor=Color [HighlightText], Font=[Font: Name=Microsoft Sans Serif, Size=8.25, Units=3, GdiCharSet=0, GdiVerticalFont=False], WrapMode=True, Alignment=MiddleLeft }} System.Windows.Forms.DataGridViewCellStyle
      RowHeadersVisible true bool
      RowHeadersWidth 41 int
      RowHeadersWidthSizeMode EnableResizing System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode
    +  Rows {System.Windows.Forms.DataGridViewRowCollection} System.Windows.Forms.DataGridViewRowCollection
    +  RowsDefaultCellStyle {DataGridViewCellStyle { }} System.Windows.Forms.DataGridViewCellStyle
    +  RowTemplate {DataGridViewRow { Index=-1 }} System.Windows.Forms.DataGridViewRow
      ScrollBars Both System.Windows.Forms.ScrollBars
    +  SelectedCells {System.Windows.Forms.DataGridViewSelectedCellCollection} System.Windows.Forms.DataGridViewSelectedCellCollection
    +  SelectedColumns {System.Windows.Forms.DataGridViewSelectedColumnCollection} System.Windows.Forms.DataGridViewSelectedColumnCollection
    +  SelectedRows {System.Windows.Forms.DataGridViewSelectedRowCollection} System.Windows.Forms.DataGridViewSelectedRowCollection
      SelectionMode RowHeaderSelect System.Windows.Forms.DataGridViewSelectionMode
      ShowCellErrors true bool
      ShowCellToolTips true bool
      ShowEditingIcon true bool
      ShowRowErrors true bool
    +  SortedColumn null System.Windows.Forms.DataGridViewColumn
      SortOrder None System.Windows.Forms.SortOrder
      StandardTab false bool
      Text "" string
    +  TopLeftHeaderCell {DataGridViewTopLeftHeaderCell} System.Windows.Forms.DataGridViewHeaderCell {System.Windows.Forms.DataGridViewTopLeftHeaderCell}
    +  UserSetCursor {[Cursor: Default]} System.Windows.Forms.Cursor
      VerticalScrollingOffset 0 int
      VirtualMode false bool
    +  Static members  
    +  Non-Public members  
    ///// dgvCollection Properties /////

    ///// dgvCollection.Rows[0].Cells[1] Properties during Dispose /////
    -  dgvCollection.Rows[0].Cells[1] {DataGridViewComboBoxCell { ColumnIndex=1, RowIndex=0 }} System.Windows.Forms.DataGridViewCell {System.Windows.Forms.DataGridViewComboBoxCell}
    +  [System.Windows.Forms.DataGridViewComboBoxCell] {DataGridViewComboBoxCell { ColumnIndex=1, RowIndex=0 }} System.Windows.Forms.DataGridViewComboBoxCell
    +  base {DataGridViewComboBoxCell { ColumnIndex=1, RowIndex=0 }} System.Windows.Forms.DataGridViewElement {System.Windows.Forms.DataGridViewComboBoxCell}
    +  AccessibilityObject {System.Windows.Forms.DataGridViewCell.DataGridViewCellAccessibleObject} System.Windows.Forms.AccessibleObject {System.Windows.Forms.DataGridViewCell.DataGridViewCellAccessibleObject}
      ColumnIndex 1 int
    -  ContentBounds {X = 1 Y = 11 Width = 0 Height = 0} System.Drawing.Rectangle
      Bottom 11 int
      Height 0 int
      IsEmpty false bool
      Left 1 int
    +  Location {X = 1 Y = 11} System.Drawing.Point
      Right 1 int
    +  Size {Width = 0 Height = 0} System.Drawing.Size
      Top 11 int
      Width 0 int
      X 1 int
      Y 11 int
    +  Static members  
    +  Non-Public members  
      ContextMenuStrip null System.Windows.Forms.ContextMenuStrip
      DefaultNewRowValue null object
      Displayed true bool
      EditedFormattedValue "" object {string}
    +  EditType {Name = "DataGridViewComboBoxEditingControl" FullName = "System.Windows.Forms.DataGridViewComboBoxEditingControl"} System.Type {System.RuntimeType}
    +  ErrorIconBounds {X = 0 Y = 0 Width = 0 Height = 0} System.Drawing.Rectangle
      ErrorText "" string
      FormattedValue "" object {string}
    +  FormattedValueType {Name = "String" FullName = "System.String"} System.Type {System.RuntimeType}
      Frozen false bool
      HasStyle false bool
      InheritedState Displayed | Resizable | ResizableSet | Visible System.Windows.Forms.DataGridViewElementStates
    +  InheritedStyle {DataGridViewCellStyle { BackColor=Color [Window], ForeColor=Color [ControlText], SelectionBackColor=Color [Highlight], SelectionForeColor=Color [HighlightText], Font=[Font: Name=Microsoft Sans Serif, Size=8.25, Units=3, GdiCharSet=0, GdiVerticalFont=False], WrapMode=False, Alignment=MiddleLeft }} System.Windows.Forms.DataGridViewCellStyle
      IsInEditMode false bool
    +  OwningColumn {DataGridViewComboBoxColumn { Name=dgvCollection_FolderId, Index=1 }} System.Windows.Forms.DataGridViewColumn {System.Windows.Forms.DataGridViewComboBoxColumn}
    +  OwningRow {DataGridViewRow { Index=0 }} System.Windows.Forms.DataGridViewRow
    +  PreferredSize {Width = 39 Height = 22} System.Drawing.Size
      ReadOnly false bool
      Resizable true bool
      RowIndex 0 int
      Selected false bool
    +  Size {Width = 121 Height = 22} System.Drawing.Size
    +  Style {DataGridViewCellStyle { }} System.Windows.Forms.DataGridViewCellStyle
      Tag null object
      ToolTipText "" string
      Value 2 object {int}
    +  ValueType {Name = "Int32" FullName = "System.Int32"} System.Type {System.RuntimeType}
      Visible true bool
    +  Static members  
    +  Non-Public members  
    ///// dgvCollection.Rows[0].Cells[1] Properties during Dispose /////

    ///// dgvCollection_FolderId /////
    -  dgvCollection_FolderId {DataGridViewComboBoxColumn { Name=dgvCollection_FolderId, Index=1 }} System.Windows.Forms.DataGridViewComboBoxColumn
    +  base {DataGridViewComboBoxColumn { Name=dgvCollection_FolderId, Index=1 }} System.Windows.Forms.DataGridViewColumn {System.Windows.Forms.DataGridViewComboBoxColumn}
      AutoComplete true bool
    +  CellTemplate {DataGridViewComboBoxCell { ColumnIndex=-1, RowIndex=-1 }} System.Windows.Forms.DataGridViewCell {System.Windows.Forms.DataGridViewComboBoxCell}
      DataSource null object
      DisplayMember "" string
      DisplayStyle DropDownButton System.Windows.Forms.DataGridViewComboBoxDisplayStyle
      DisplayStyleForCurrentCellOnly false bool
      DropDownWidth 1 int
      FlatStyle Standard System.Windows.Forms.FlatStyle
    +  Items {System.Windows.Forms.DataGridViewComboBoxCell.ObjectCollection} System.Windows.Forms.DataGridViewComboBoxCell.ObjectCollection
      MaxDropDownItems 8 int
      Sorted false bool
      ValueMember "" string
    +  Static members  
    +  Non-Public members  
    ///// dgvCollection_FolderId /////

    Monday, December 19, 2005 8:53 AM
  • Tell me a bit more about what your grid looks like -- you say the combobox column is column 1. How many columns do you have? Are you databinding the grid and combobox column through a BindingSource? Did you use the designer to databind everything or did you write code to databind the grid/combobox column? Did you add any code to the Dispose event? If you have a simple repro, can you open a bug for it? You can use the following link: http://lab.msdn.microsoft.com/productfeedback/Default.aspx  

     

    -mark

    DataGridView Program Manager

    Microsoft

    This post is provided “as-is”

     

    Monday, December 19, 2005 7:28 PM
  • Mark,

    The column count does not seem to matter.  It could be two, it could be twenty.
    The databinding for both the DataGridView and the DataGridViewComboBoxColum are BindingSources.
    It does not seem to matter whether the designer generates the code or I do.  The exception happens in either case.
    I did not modify any Dispose event or methods. I did not inherit any classes.

    To reproduce:

    Create a Panel (pnl).

     pnl.Dock = Fill

    In pnl, create a DataGridView (dgv):

    dgv.DataSource = someBindingSource
    dgv.AutoResizeRowsMode = AllCells or DisplayedCells (either one causes the exception)
    dgv.Dock = Fill

    Change one of the DataGridView Columns (dgvc) to a DataGridViewComboBox:

     dgvc.DataSource = someOtherBindingSource
     dgvc.DisplayMember = DescriptionField
     dgvc.ValueMember = ForeignKeyForDescriptionField

    The records for the binding sources should have data in the fields that are sufficient in length to force the width of the displayed rows to extend past the width of the DataGridView.  Exceptions are thrown during Dispose when the sum of all the DataGridViewCell.Size.Width properties of the DataGridRow.Cells collection exceeds the DataGridView.Width property.  As long as the sum of the widths of all the cells is less than the width of the data grid view, the exception is not thrown.

    What really piques my curiosity is why the framework should be concerned with formatting during disposal.  I do not know what goes on behind the scenes, but it does not seem logical to me to be calling formatting methods during disposal.  Why are the disposal methods concerned with formatting?

    Monday, December 19, 2005 8:32 PM
  • Thanks for the repro steps. The issue is that the Form's dispose method is first disposing the datasource that the combobox column is using before it is disposing the DataGridview. This is the same as not databinding the combobox column at all. This only causes a problem when autosizing the rows or autosizing the combobox column since removing the combobox column's datasource causes the row/column to perform autosize layout. As part of the layout, the combobo cell needs to retrieve the FormattedValue, which raises the DataError since the cell cannot find a match in the combobox (since the combobox column's datasource is now null).

     

    The easiest way to fix this is to change the autosize mode of the grid in the form's dispose method. Alternatively you can manually databind the combo box column, including manually creating the BindingSource. This will allow you to manually dispose the combobox column's binding source on your own -- after the grid has already disposed.

     

    -mark

    DataGridView Program Manager

    Microsoft

    This post is provided “as-is”

     

     

    • Proposed as answer by DR MAQ Monday, June 22, 2009 9:20 PM
    Monday, December 19, 2005 9:21 PM
  • You are more than welcome, Mark.  Thank YOU for the DataGridView!

     

    You raise an interesting point, however.  There seems to be a problem with the way the form disposes of its components.  Should there not be a logical order taken during disposal?  Should the fix not be there instead of in the hands of the developers?

    Monday, December 19, 2005 10:11 PM
  • I had thought the same thing as I investigated this problem. Currently we do not have any way to specify any dependency for disposing, but in 2005 we did create better support for dependencies when initializing controls/components. Sounds like we need to create some new support to deal with this type of problem.

     

    I've opened a bug to address this issue hoping that we can do something in the next version.

     

    -mark

    DataGridView Program Manager

    Microsoft

    This post is provided “as-is”

     

     

    Monday, December 19, 2005 10:35 PM
  • Mark, how about releasing a new DataGridViewComboBoxColumn that would handle this problem. It would not have to be something that Microsoft oficially supports, maybe something like a working code sample.
    Monday, December 19, 2005 10:48 PM
  • I wish I could, but unfortunately this requires changes outside of DataGridView to support this, since the DataGridViewComboBoxColumn doesn't know that a dispose has started on the Form. It would require changes at the Form (or Control) level and up.

     

    -mark

    DataGridView Program Manager

    Microsoft

    This post is provided “as-is”

     

    Monday, December 19, 2005 10:51 PM
  • I ran into the same issue and tried all of the usual and unusual tips.

    I stumbled on this one myself: I have a databound datagridview and I kept getting the same error on form close and cellendedit

    This is all I had to do to fix it:

    datagridviewcomboboxcolumn6.Value = ""

    In the cellvaluechanged event I assigned a default value to the datagridviewcombobox and all errors went away.

    Allen Simmons

    "Will computer for work"

    Sunday, January 8, 2006 7:08 AM
  • The solution that I have been using is to set the DataGridView.AutoSizeColumnsMode to DataGridViewAutoSizeColumnsMode.None in FormClosing method for all the datagrids that I use.  It's quick, simple, and requires very little code.

    dgvvModelFile.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;

    Sunday, January 8, 2006 7:22 AM
  • Note that the problem also occurs if Rows are set to autosize, (for example in conjunction with wrapping in a text box column)  and there is a combobox column in the grid. So you also need to add the following to Jerry's example if you use row autosize:

    dgwModelFile.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None

    Monday, January 9, 2006 12:14 AM
  • I get the same problem in the Visual Studio 2005 Team Edition.  When the DataGridComboBoxColumn is set using the Wizard, and the AutoSizeMode is "NotSet", the error occurs repeatedly.  It looks like it is trying to Update the Cell value from a DataAdaptor and is putting blanks out.

    When AutoSizeMode is set to "None", the error goes away.

    I am using a SQL Server 2000 database for the underlying store.

    Monday, January 9, 2006 8:04 PM
  • Good tip Bob.

     

    Monday, January 9, 2006 11:52 PM
  • Hi Mark,

    I had the same problem, but for me it was not because of the autosize Property but because my DataGridView had the property ReadOnly on true... When binding the DataGridViewComboBoxCell I got the same error.

    Now everything works fine for me!

    Btw, Great control!!!

    Regards Simon

    Wednesday, January 18, 2006 10:12 PM
  • I'm having the exact same problem.  I do have a value in my grid results that does not match to a value in my dropdown.  I changed the value to match and I changed the autosize attribute to "Notset". This did alleviate the problem. 

    However, what if the data does not match something in the Drop-Down?  After all, this is an editable field.  I should be able to either type in a new value, or select one from the list.  Correct?  So what am I missing here?  Can we extend the comboboxcolumn so that it will add the new value to it's list?  Any help would be appreciated.  Thanks!

    FYI...I am using a databound DataGridView with a bindsource as well as my Drop-Down column is also databoud with a bindingsource.

    Thursday, February 9, 2006 5:06 PM
  • How do you do that when value is not a member of system.datagridviewcombobox?
    Thursday, May 11, 2006 2:56 PM
  • Adding the following line of code to the constructor of my User Control solved the problem for me.

    components.Add(this.theDataGridView);

    Monday, July 17, 2006 4:05 PM
  • I am also facing this problem and i have tried all suggested methods but still not solution.
    My problem is that i am using a simple array of objects to bind with the DataGridView.
    But i need first column as ComboBox . As long as i just contented with default columns the grid shows the results perfectly but when i replace the first column with DataGridViewComboBoxColumn , it start prompting the error dialog at the start of the form.
    Interestingly when i ran debugger , it only shows the error when the form finished its init phase. (as i m doing all this stuff after initalizecomponent).
    The sample code is like that;

       DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
                col.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
                col.DataPropertyName = "Address";
                col.HeaderText = "Address";

                this.dataGridView3.AutoSize = false;
                this.dataGridView3.Columns.Add(col);
                //companies collection return the collection of company that contain address and name
                this.dataGridView3.DataSource = comapnies_collection.items;


    Thanks in advance;
    Wednesday, September 20, 2006 4:14 PM
  • It does not look like you are setting the column's (col's)DataSource, DisplayMember, and ValueMember.  I'm just guessing since I do not know what error message you are getting.

     

    Wednesday, September 20, 2006 8:23 PM
  • I managed to fix this problem by making the ValueMember and the DisplayMember the same for my DGVcomboxBox, although I dont really see the relevance.

    Mike

    Tuesday, September 26, 2006 2:03 PM
  • I sorted the problem some how and Mike suggested me to have same Value and DisplayMember yes mike it works as i did in the same way. But now i need the key associated with the description . Therefore Display/Value combination suites here very well.
    Therefore, i want to ask is there any other way to do it and having different fields for Display and Value member,
    Friday, September 29, 2006 3:09 PM
  • I am having a similar problem but I am getting the error when I scroll the grid. Each time I scroll up or down the error is being displayed. I tried every suggestion that was posted but nothing seems to work. To recreate this, populate and bind the DataSource property of the DataGridView with a data source that has enough rows that would force you to scroll to the bottom to view the last record.

    Please let me know if you can help me with this one!

    Thanks in advance...

    HERE IS MY CODE:

    this.Patient_Provider.DataSource = ds.Tables[0];

    this.Patient_Provider.ValueMember = Constants.Providers.ProviderNo;

    this.Patient_Provider.DisplayMember = Constants.Providers.ProviderName;

    this.Patient_Provider.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;

    Friday, September 29, 2006 5:18 PM
  • Marlon,

    Are your "Constants.Providers.x" strings?  Just a wild guess.

     

    Friday, September 29, 2006 5:28 PM
  • Yes they are... thanks
    Friday, September 29, 2006 5:30 PM
  • I figured out what the problem was. If I bind the ValueMember and there is a null value, there is no default value for the DataGridViewComboBox can use to handle null values. When scrolling, the combo box is throws an error becuase of these null values. I have a work aournd:

    Let's say I am populating a State combo box with all the states. Then I bind my state code to the combo box. If my data does not have a state value for a record then this would cause the problem. My work around is to add a "" (blank) value to represent the records that do not have a state value.

    Friday, September 29, 2006 7:20 PM
  • Remember that the type of data of new value need be the same. (My example it's in C#)

    private void dataGridView1_CellValueChanged( object sender, DataGridViewCellEventArgs e )

    {

    if (e.ColumnIndex == 0)

        {

            object obj = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

            MessageBox.Show( obj.GetType().ToString() );

        }

    }

    The MessageBox show "byte" then first you need cast to "byte" before asign the value

    this.dataGridView1.Rows[0].Cells[0].Value = Byte.Parse(1);

     

    Good Luck.

    Wednesday, October 4, 2006 6:37 AM
  • yeah you are right , i figured it out as well and now atleast working fine , lets see what QA find in it ? :)
    Tuesday, October 10, 2006 7:38 PM
  •  Simon Telling wrote:
    Mark,

    That sounds resonable. But I receive the error while closing the form.

    Simon

    Using C# - Visual Studio 2005 Winforms:

    I have a related problem in that the error message gives the exception: datagridviewComboBoxCell value is not valid.

    However I am not using auto resize, nor am I resizing the datagrid manually:

    What I am doing is I have a default filter for my as below

    //Primary Select - Declared in the Initialsation stage so it can be referenced as the default

    private String Job_DefaultFilter = "SELECT * FROM Job LEFT JOIN JobStatus ON Job.job_Status = JobStatus.js_ID WHERE (((JobStatus.js_ShowOnDispatch)=1)) Order by job_DispatchTime;";

    //then inplemented in the load procedure of the form
                Job_command.Connection = CN;
                Job_command.CommandText = Job_DefaultFilter;
                Job_dataAdapter.SelectCommand = Job_command;
                Job_commandBuilder.DataAdapter = Job_dataAdapter;
                Job_dataAdapter.Fill(Job_dataTable);

    //For the secondary sort (When the button is selected)
    //The Select Statement

                this.Job_command.CommandText = "SELECT * FROM Job LEFT OUTER JOIN JobStatus ON job_Status = JobStatus.js_ID WHERE js_ShowInDispatched = 1 ORDER BY Job.job_DispatchTime;";

    //Then  Clear and the table and refill it (required because of table join & filter statement from  source)
    //also unless the table is cleared first the new data is appended to the existing table.
                this.Job_dataTable.Clear();
                this.Job_dataAdapter.Fill(this.Job_dataTable);


    // The connection (CN) is already defined and is working.

    Any help will be very much appreciated

    Monday, October 30, 2006 8:13 AM
  • I'm having the same problem, with a DataGridView bound to a BindingSource, which is in turn bound to a business object. Everything's fine until I close the form, at which point I get DataError events firing, with a DataGridViewDataErrorEventArgs.Context of ( PreferredSize | Formatting )...

    Here's the work-around that's solved the problem for me. In the FormClosing handler, explicitly detach the BindingSource like so:

    private void MyForm_FormClosing(object sender, FormClosingEventArgs e) {~
     
      // (insert code to perform form-close validations here)

        // right at the end, if we're still closing the form
      
      if (! e.Cancel) {
          //assign the binding source to the type rather than the instance.
          myBindingSource.DataSource = typeof(MyObject);
        }
    }

    The bindingSource.DataSource = typeof(MyObject) syntax isn't something I've seen documented, but as far as I can ascertain, it lets you detach and re-attach binding sources that are bound to business objects, while maintaining their bindings and validation rules, etc.

    Thursday, November 2, 2006 4:08 PM
  • i have the same problem and it is becoming a little frustrating. I have not even changed anything on the particular form that is throwing the error.
    Thursday, March 1, 2007 10:07 AM
  •  Mitch L wrote:

    I found a work around. If I take out the databindings for the grid before closing the form I don't get the error.



    Me
    .dgvStoreVisit.DataSource = Nothing
    Me.Close()

     


     

    This solved my problem to

     

    Thank you very much, mitch !!!!

    Saturday, March 31, 2007 6:46 PM
  •  Mitch L wrote:

    I found a work around. If I take out the databindings for the grid before closing the form I don't get the error.



    Me
    .dgvStoreVisit.DataSource = Nothing
    Me.Close()

     


     

    This solved my problem to

    thanks very much, mitch

    Saturday, March 31, 2007 7:08 PM
  • This helped a lot.  I was getting this error popping up for each DataGridViewComboBoxCell that had any information in it when I was closing (as many as 20 at exit).

    Fixed the problem by using the code below prior to closing the form:

    DataGridViewName.Dispose()

    Thanks,
    Eric
    Tuesday, April 17, 2007 4:20 PM
  • I to had this problem, and thought i might post my solution.  Appologies if its already in the post:

     

    I noticed that the error only showed when my data grid first loaded, but then more importantly noticed that it occured when i scolled the top of the grid into view after having been at the bottom.  I then noticed that mousing over a single combo box cell caused the error.

     

    So looking in the database manually i found that sure enough, that cell contained a value that is not in the combo box list of values.  Probably a relic from my development?  Who knows.  but its a good check to ensure that your database contains only values listed in the combo box, including spaces after text.

    Wednesday, April 25, 2007 12:50 PM
  • But I will absolutely have values in the first table that will NOT be in the table the combo box looks at.  I just want spaces or nulls or something to show then.
    Wednesday, April 25, 2007 3:06 PM
  • I have set up a test form that contains a DataGridView from dragging a table (tableA) over from the DataSoure Tab.  I then edited the columns and changed one column to a combobox.  It contains the key to tableB.  So DatPropertyName is still set to the key value in table A.   For DataSource, I drilled down through the dataset until I found my tableB.  Display member is the text field from table B, ValueMember is the key field from tableB.  I have set AutoSizeMode to None in the Edit columns.  I have gone to properties of the DGV, and ensured AutoSizeColumnsMode aned AutosizerowsMode are set to None.  I verified that all values in tableA key field are present in tableB. 
    When I run it, I get the "DataGridViewcomboBoxCell value is not valid when it goes to paint that combo box on every row, then just displays the original key value.

    Any ideas?

    Thanks,
    Steve
    Wednesday, April 25, 2007 3:54 PM
  • Hi all,

     

    I've got the same problem too. And I also have a solution.

    First, may I describe the situation the problem occurs. The context is that I've got 2 entities. Let's call Entity1 and Entity2. All are typed datasets. The DataGridViewComboBoxColumn's datasource is bound to a BindingSource which DisplayMember = Entity1's name and ValueMember = Entity1's id. The DataGridView where DataGridViewComboBoxColumn belongs is bound to a BindingSource with DataSource = Entity2. Of course, there is a relation between these entities. My Entity2 have many fields, one of them relate to Entity1's id. When I populate data from database to these entities, it is OK. No problem. But when I update the Entity2 to the database by following code

     

    // These following codes run in a separate thread

    DataTable temp = entity2.GetChanges();

    new Entity2DataAdapter().Update(temp);

    entity2.Merge(temp);

     

    the problem occurs. The Value of the DataGridViewComboBoxCell was set to an anonymous value (this happens to all the cells within the DataGridViewComboBoxColumn). Strangely, that anonymous value is the value of one of my Entity2's fields. Of course, it makes the application fail with message "DataGridViewComboBoxCell value is not valid".

     

    My solution to this problem is: I turn off the ListChanged event of binding source to the Entity2 before updating it by calling:

     

    bsEntity2.RaiseListChangedEvent = false;  // bsEntity2 is the BindingSource with DataSource = Entity2 and it is the DataSource of my DataGridView control

     

    After updating to database, I turn it on and reset bindings

     

    bsEntity2.RaiseListChangedEvent = true;

    bsEntity2.ResetBindings(false);

     

    The DataGridView operates as I command. No exception. No message box. No need to turn off the autosize mode.

     

    This workaround helps me guess the background working of the DataGridView control (it's just only my guess). I think the DataGridView update its UI on another thread (I'm pretty sure of it). Why did I think like this? Have you recognized that although your DataGridView have 1 row or 1000 rows, it scrolls smoothly everytime we drag its scrollbar?. I think the development team of DataGridView control have designed to drive the control to read and display data on a thread separate from the main UI thread. And this makes the problem we face. Everytime we change the underlying list of BindingSource, update the binding dataset, or just close the main form, the DataGridView doesn't know about that. And it will display and manage the data, despite it is deleted or changed. We have a little chance to see this problem if we update our dataset on the main UI thread (because there are only two threads operating on the same data, the main UI thread and the thread that DataGridView control uses). If you create a thread and call any data changing functions, the problem occurs more often. The more threads run, the more chance we face the problem. So I decide to use the code pattern mentioned above. It prevents the DataGridView control access to the datasource while we're operating on it. It's just a little trick to synchronize data access.

     

    That's all I know about this case. I'd like to hear your idea and suggestion.

    Thanks.

    Nguyen Thanh Ha

    Friday, June 15, 2007 7:00 PM
  • I just want to report my experience as i had the same symptoms as many posts, but a different solution.

     

    I had a similar errors as most posters. I was trying to use a DataGridViewComboBox to display an enumeration type. The type was encoded as integer in the data records and needed to be encoded as a string in the combo box for display.

     

    I spent 5 hours on this until i came across the solution. I tried just about every trick in this thread, but the message was litterally true: The binding of the combo col was to an array of strings i generated from the enum yet the record value was int, so in fact the combo could not find an entry in the string list to match the integer value.

     

    I created a property in the top level object to convert the enum to/from string and it now works ok.

     

    My poor brain hurts...

     

    tnx to all the contributers here.

    pp.

    Thursday, September 27, 2007 6:54 PM
  • I've almost tried everything that you guys said. Setting the display/value member was the one that worked.
    Friday, October 26, 2007 9:00 AM
  •  

    i my situation that i have found the problem , there is two problem :

     1- if the DataTable Field(Child Field) have a values dont in the DataTable List (Parent Field).

     2- the Type of the two Field must be the same (child Filed and the Parent Field .  

    Friday, October 26, 2007 9:53 AM
  • I used this solution, and it works!!!!!!!

     

    Thursday, March 6, 2008 7:18 PM
  • I just had to implement this workaround, and I've got SP1 on my VS 2005 installation.  Is there a patch for this???  Is this fixed in VS 2008???

     

    Thanks,

    Bob

     

     

    Wednesday, April 9, 2008 9:26 PM
  •  shiflettre wrote:

    I just had to implement this workaround, and I've got SP1 on my VS 2005 installation.  Is there a patch for this???  Is this fixed in VS 2008???

     

    Thanks,

    Bob

     

     



    This is not fixed in .net 3.5!
    Saturday, October 18, 2008 1:17 PM
  • bsEntity2.RaiseListChangedEvent = false;  // bsEntity2 is the BindingSource with DataSource = Entity2 and it is the DataSource of my DataGridView control

     

    After updating to database, I turn it on and reset bindings

     

    bsEntity2.RaiseListChangedEvent = true;

    bsEntity2.ResetBindings(false);

     

    The DataGridView operates as I command. No exception. No message box. No need to turn off the autosize mode.

    hi Sherlock Holmes ,

    im trying ur suggestion,

    but my VS says that the 'System.Windows.Forms.BindingSource' doesn't contain a definition for 'RaiseListChangedEvent'

    is there anything i missed? please check it again. thanks,


    Wednesday, May 13, 2009 5:14 AM
  • By changing the combobox's AutosizeMode to NotSet has fixed my problem
    Thanks for the workaround
    Maqsood Ahmad
    Monday, June 22, 2009 9:22 PM
  • I created a 'filter row' in a datagridview (only that row was editable), When i filtered the data and tried to select a row the error occured.
    By implementing the solution/WA of noam error doesn't  occur anymore. Is it a bug?
    • Proposed as answer by jllj3 Wednesday, February 23, 2011 8:19 PM
    • Unproposed as answer by jllj3 Wednesday, February 23, 2011 8:19 PM
    Friday, March 12, 2010 10:48 AM
  • Hello,

    I have discovered a new twist. The column datatype in the database that the datagridview is bound to was set to nchar(20) which ends up adding spaces (does not match the items list). I changed the datatype to nvarchar and removed the spaces and the problem went away.

     

    John Love

    • Proposed as answer by rootyosi Tuesday, June 21, 2011 12:46 AM
    Wednesday, February 23, 2011 8:24 PM
  • just found out, the problem occurs when your trying to display a default value on a combobox in a datagridview without filling it up first with items from your database. to make it short. fill the combobox first with items from your database then place your code that display default value to your combobox.

    Wednesday, March 23, 2011 2:51 AM
  •  

    After testing several solutions I find out that a little cast in the query that fill the combo solved the issue.

    here was my issue

    My datagridview is filled with a query A that return several columns and I decided to convert one of them (AssigneeID) to a combobox

    the Query A provide Assignee ID's that is SMALLINT type

    The Query B provide the list of all Users with the ID SMALLINT and Name VARCHAR(250)

    I don't know why but in the C# solution the ID from query B is not recognised as the same type as the AssigneeID from the Query A and this is why I was getting this stupid error.

    doing a little cast on the ID in query B solved the issue

     

    SELECT CAST(dbo.tbl_Employee.ID as INT) as ID, dbo.tbl_Employee.FullName
    FROM dbo.tbl_Employee

    Perhaps there is a way to force DataGridViewComboBoxColumn to the correct type
    I tried to set the valueType but it's not working

                    DataGridViewComboBoxColumn Assignee = ((DataGridViewComboBoxColumn)(this.dataGridView_TasksDetails.Columns["AssigneeID"]));
    
                    //Customize the column to receive the Assignee List 
                    Assignee.ValueType = typeof(int);

    hope that will help

     


    • Edited by denfer Friday, September 16, 2011 1:54 PM
    • Proposed as answer by ankky Wednesday, July 17, 2013 12:30 PM
    Friday, September 16, 2011 1:44 PM
  •     private void dvItems_DataError(object sender, DataGridViewDataErrorEventArgs e)
            {
                e.Cancel = true;
            }



    Wednesday, July 17, 2013 12:31 PM
  • I was struggling with this bug for more than one day and your answer showed me the light!

    As mentioned in the next posts turning off the AutoSizeColumnsMode or AutoSizeRowsMode in FormClosing event solved the problem.

    Thanks!

    Wednesday, October 9, 2013 10:50 AM
  • I had the same problem and your advice really worked.

    But the interesting part is that I'm using Visual Studio 2013 with .Net 4.5 and still the bug exists!!!!

    I was kind of shocked when I got this error again, I had it before on .Net 2 but it still exists!

    Could you please make this bug a priority or something, many other people may have it, I know that right now most of my own apps are with WPF but still I think it would be nice to remove this bug once and for all.


    Ghamsary

    Saturday, July 19, 2014 10:40 PM
  • I had the same problem and your advice really worked.

    But the interesting part is that I'm using Visual Studio 2013 with .Net 4.5 and still the bug exists!!!!

    I was kind of shocked when I got this error again, I had it before on .Net 2 but it still exists!

    Could you please make this bug a priority or something, many other people may have it, I know that right now most of my own apps are with WPF but still I think it would be nice to remove this bug once and for all.


    Ghamsary

    Hello,

    You can report this via the following link

    https://connect.microsoft.com/


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

    Sunday, July 20, 2014 3:16 PM
  • @PassePartout I have the EXACT same problem and wish you'd posted some example code. How precisely did you solve it? What is the top level object?? 
    Thursday, January 22, 2015 8:12 AM