Filling DataGridView ComboBox programatically in unbound mode?

无人久伴 提交于 2020-03-25 16:13:12

问题


The following code snippet (The question is here: http://www.vbdotnetforums.com/winforms-grids/10038-fill-datagridview-combobox-column.html) is for filling a combobox cell in a datagridview in unbound mode:

Dim dgvcc As DataGridViewComboBoxCell
dgvcc = DataGridView1.Rows(2).Cells(0)
dgvcc.Items.Add("comboitem1")
dgvcc.Items.Add("comboitem2")

I'm trying to do likewise but I can't help but notice that the casting operation is invalid and that's the exact error VB gives me.

I've tweaked the code a bit and tried it but still I get the same casting error:

Dim dgvcc As Windows.Forms.DataGridViewComboBoxCell
dgvcc = Window.DataGridView1.Rows(2).Cells(0)
dgvcc.Items.Add("comboitem1")
dgvcc.Items.Add("comboitem2")

Window is the name of the form in which the DataGridView1 objet is.

Can anyone please show me an easy method to fill a combobox in a datagridview in unbound mode. You can as well tell me why did it not work for and it did work for others?


回答1:


You are taking the GridViewComboBoxCell, instead take GridViewComboBoxColumn and refer the code snippet given below, which will work fine

    Dim cbState As DataGridViewComboBoxColumn
    cbState = DataGridView1.Columns("cbCol1")
    cbState.Items.Add("Karnataka")
    cbState.Items.Add("Andhra Pradesh")

The above code will give a result like below for the DataGridview.

EDIT :

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim cbState As DataGridViewComboBoxColumn
    cbState = DataGridView1.Columns("cbCol1")
    cbState.Items.Insert(0, "Karnataka")
    cbState.Items.Add("Andhra Pradesh")

End Sub

Private Sub DataGridView1_CellFormatting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    If e.ColumnIndex = 0 Then
        e.Value = "Karnataka"
    End If
End Sub


来源:https://stackoverflow.com/questions/27655152/filling-datagridview-combobox-programatically-in-unbound-mode

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