简体   繁体   中英

Filling DataGridView ComboBox programatically in unbound mode?

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 it did not work for me and why it is working for others?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM