DataGridComboBoxCell - Can't Fill Values Programmatically

邮差的信 提交于 2021-02-11 12:36:01

问题


I'm filling a DataGridView with 2 columns, a DataGridViewTextBoxColumn for a name label, and a DataGridViewComboBoxColumn to act as a dropdown for selecting an SQL Column name to map to the name.

I'm going for a loop through my names, and creating a row for each of them. Each row should display the name of a field (String object), and in the other column should be a combo box (values are within a List (Of String)). I keep getting an exception raised that says 'the value is not valid':

For Each sourceColumn As String In sourceColumnList
    Dim item As New DataGridViewTextBoxCell
    Dim destcombo As New DataGridViewComboBoxCell
    item.Value = sourceColumn
    destcombo.Items.AddRange(sqlColumnSelectionList.ToArray())

    '    ERROR IS HERE, REFERRING TO INVALID COMBO BOX |
    '                                                 \|/
    list_Destination_SQLMap.Rows.Add(sourceColumn, destcombo)
Next

I've googled around but can only find examples of how to fix this problem with data sources that are bound, not unbound. I know I'm missing something, this is the first time I've used a DataGridView.


回答1:


When adding a DataGridViewComboBoxColumn you also need to set its DataSource property to a valid source. A DataTable if you get the data from a database or List (Of T) - Your List (Of String) will work just fine.

Add the code below AFTER you have created and populated the sqlColumnSelectionList. (Don't forget to change the variable name column2 to whatever you named it)

column2.DataSource = sqlColumnSelectionList

It is important to remember that the DataGridViewComboBox works just like a normal ComboBox when it comes to initialisation and general usage.

Once you have that done, when adding rows you should change this line:

list_Destination_SQLMap.Rows.Add(sourceColumn, destcombo)

to be:

list_Destination_SQLMap.Rows.Add(sourceColumn, "")

This will add the new row to the DataGridView with an entry in the Text column matching the name of the field (as per your description) and the second column will be blank allowing the user to select the value from the drop down.

If you need the second column to be pre-selected to a value, replace the empty string with that value.

The DataGridViewComboBoxColumn only needs to be populated the once, and not every time a new cell is added to the DataGridView.



来源:https://stackoverflow.com/questions/55199674/datagridcomboboxcell-cant-fill-values-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!