How do I solve this dynamic datagridview combobox problem? (VB.Net)

JohnnyBCJ used Ask the Experts™
I'm dynamically creating a number of datagridviews. One of the columns is a combo box column.
The list of items in the combo box is created by a datasource. Rows are manually added (datagridview.rows.add....).

If I attempt to add a row with a value that is not in the combo box column list, I get the following error:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

What I want to happen is instead of this error occurring, I want the combo box column data source to be dropped and have value that is being added to be the only item in this combo box column for this row.

How can I manage to do this?

The code that is related to this problem is below:
Dim cboDel As New DataGridViewComboBoxColumn


myConnection = New SqlConnection(frmLogin.strConnection)
Dim da As New SqlDataAdapter("SELECT ... from tbl", myConnection)
Dim ds As New DataSet

cboDel.DataSource = ds.Tables(0)
cboDel.DisplayMember = "..."
cboDel.ValueMember = "..."
cboDel.Name = "..."
cboDel.HeaderText = "..."
cboDel.MaxDropDownItems = ds.Tables(0).Rows.Count + 1

Function that create DGV / add Rows...

Dim DGV As New DataGridView

'Add Columns
DGV.Columns.Add("0", "0")
DGV.Columns.Add("1", "1")
DGV.Columns.Add("2", "2")
DGV.Columns.Add("3", "3")
DGV.Columns.Add("4", "4")
DGV.Columns.Insert(5, cboDel.Clone)
DGV.Columns.Add("6", "6")
DGV.Columns.Add("7", "7")

DGV.Location = New Point(intDgvX, intDgvY)



For intRowAdd = 0 To dsInfo.Tables(0).Rows.Count - 1
DGV.Rows(intRowAdd).Cells("cboDel").DataGridView.DataSource = dsInfo.Tables(0).Rows(intRowAdd)("DELIVERY").ToString


Open in new window

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2012
Top Expert 2014

Thanks for the suggestion CodeCruiser.
Although what you suggested is a possible solution, I managed to solve this problem by going a different route.

Before adding the row, I tested to see if the value related to the combo box was valid.
If it was, I added the row.

If it wasn't I did the following:
- Set the value to added as blank
- Added the row
- Cleared the datasource of the combo box cell
- Set the datasource to be the value that was going to be added
- Changed the cell to be the value added

This took me a fair bit of trial and error to figure out. Hopefully this will help someone that might have the same problem as me in the future.

Thanks again.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial