InvalidOperationException on DataGridView.Rows().Cells.RemoveAt(index)
-
Friday, July 22, 2011 8:04 PM
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( _
The exception I get is "Collection already belongs to a DataGridView control. This operation is no longer valid."
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
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
All Replies
-
Saturday, July 23, 2011 2:41 AMThat 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:57 AM
dgv.Rows(WhichRowClicked).Cells.RemoveAt(dgvOutCol) '<<<<<<<<< exception occursYou 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
Mitja- Proposed As Answer by Helen ZhouModerator Thursday, July 28, 2011 5:37 AM
-
Thursday, July 28, 2011 5:41 AMModerator
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 http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/8019f5b2-5777-4da5-8342-a2c10fca89db
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 eBob.com Saturday, August 06, 2011 12:48 AM
-
Saturday, August 06, 2011 12:47 AMGreat example Helen. Thanks.


