InvalidOperationException on DataGridView.Rows().Cells.RemoveAt(index)



    I have an unbound data grid view in which I have a column which starts out with all cells being a ComboBox DropDown.  When the user selects an item from a drop down list I want to replace the ComboBox in that cell with a TextBox.  Here's the code for my event handler:

    Private Sub ComboBox_SelectedIndexChanged( _
            ByVal sender As Object, ByVal e As EventArgs)

            Dim comboBox1 As ComboBox = CType(sender, ComboBox)

            Dim NewTextboxCell As New DataGridViewTextBoxCell
            NewTextboxCell.Value = comboBox1.SelectedItem.ToString
            dgv.Rows(WhichRowClicked).Cells.RemoveAt(dgvOutCol)  '<<<<<<<<< exception occurs here
            dgv.Rows(WhichRowClicked).Cells.Insert(dgvOutCol, NewTextboxCell)

        End Sub

    The exception I get is "Collection already belongs to a DataGridView control. This operation is no longer valid."

    That just makes no sense to me.  The WhichRowClicked value is correct.  And the dgvOutCol value is correct.

    Any help will be appreciated.

    Thanks,  Bob


    Friday, July 22, 2011 8:04 PM


All replies

  • That is because you might have added the column itself as ComboBox type during design time of the dataGridView. Hence it is not possible now.
    Please mark this post as answer if it solved your problem. Happy Programming!
    Saturday, July 23, 2011 2:41 AM
  •  dgv.Rows(WhichRowClicked).Cells.RemoveAt(dgvOutCol) '<<<<<<<<< exception occurs 

    You cannot remove one cell. Think logically? Where can they go the rest of the cell in that column and cells in that row?

    Impossible. Or you remove whole column or whole row.


    Solution: you can make a new cell instead, type of DataGridViewTextBoxCell.

    Private Sub ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs)
    	Dim combo As ComboBox = TryCast(sender, ComboBox)
    	Dim _value As String = combo.SelectedItem.ToString()
    	Dim textCell As New DataGridViewTextBoxCell()
    	Dim col As Integer = dgv.CurrentCell.ColumnIndex
    	Dim row As Integer = dgv.CurrentCell.RowIndex
    	dgv(col, row) = textCell
    	dgv(col, row).Value = _value
    End Sub

    • Proposed as answer by Helen Zhou Thursday, July 28, 2011 5:37 AM
    Saturday, July 23, 2011 2:57 AM
  • Hello eBob,

    For a more complete demo about chooseing from a comboBox, but when leaving, the cell becomes a textbox with the value you choose from the combobox, you can refer to this thread which Mitja Bonca had given a excellent sample


    Helen Zhou [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Saturday, August 06, 2011 12:48 AM
    Thursday, July 28, 2011 5:41 AM
  • Great example Helen.  Thanks.
    Saturday, August 06, 2011 12:47 AM