vb.netdatagridviewdatagridviewcombobox

Creating Dynamic DataGridViewComboBoxCells


So here is my situation. I have a DataGridView, which has two columns that I am trying to set up as DataGridViewComboBoxColumns called "Received" and "Backordered".

The point of these combo boxes is to create a drop down menu to select how many items are received/backordered when my company receives a shipment. This program will mainly be run on a touch screen setup with no mouse or keyboard, which is why I am opting to use Combo Boxes as opposed to just asking for general user input.

I am attempting to set up the DataGridView as follows:

'Setup of Combo Box Columns
'shipmentData is the name of the DataGridView
Dim receiveCol As New DataGridViewComboBoxColumn()
receiveCol.HeaderText = "Received"
receiveCol.Name = "Received"
shipmentData.Columns.Add(receiveCol)
Dim backorderCol As New DataGridViewComboBoxColumn()
backorderCol.HeaderText = "Backordered"
backorderCol.Name = "Backordered"
shipmentData.Columns.Add(backorderCol)

The above code is in the New() Sub for when the form is created. I am trying to load the data into the ComboBoxes as follows:

Dim rowNum As Integer = 0
For Each op As OrderPart In OrderData.GetPartList()
    If op.AmountOrdered > 0 Then
        shipmentData.Rows.Add()
        shipmentData.Rows(rowNum).Cells("PartNumber").Value = op.PartNumber
        shipmentData.Rows(rowNum).Cells("Description").Value = op.Description
        shipmentData.Rows(rowNUm).Cells("Ordered").Value = op.AmountOrdered
        For it As Integer = 0 To op.AmountOrdered
            CType(shipmentData.Rows(rowNum).Cells("Received"), DataGridViewComboBoxCell).Items.Add(it)
            CType(shipmentData.Rows(rowNum).Cells("Backordered"), DataGridViewComboBoxCell).Items.Add(it)
        Next
        rowNum = rowNum + 1
    End If
Next

Now when I run the code, the ComboBoxes are created, and their data is added. However whenever I select a data value from the combo box list, and then try to move to another sell I get the following error:

System.ArgumentException: DataGridViewComboBoxCell value is not valid.

Why am I getting this error, and how do I fix it? I can't seem to figure out what it is I am doing wrong in my code.


Solution

  • Although I don't know why are adding incrementing numbers to your dropbox, but if you intend to do that, change your code to the following:

    For it As Integer = 0 To op.AmountOrdered
        CType(shipmentData.Rows(rowNum).Cells("Received"), DataGridViewComboBoxCell).Items.Add(it.ToString())
        CType(shipmentData.Rows(rowNum).Cells("Backordered"), DataGridViewComboBoxCell).Items.Add(it.ToString())
    Next