简体   繁体   English

在未绑定模式下以编程方式填充 DataGridView ComboBox?

[英]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:以下代码片段(问题在这里: http : //www.vbdotnetforums.com/winforms-grids/10038-fill-datagridview-combobox-column.html )用于在未绑定模式下填充 datagridview 中的组合框单元格:

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.我正在尝试做同样的事情,但我不禁注意到强制转换操作无效,而这正是 VB 给我的错误。

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. Window是 DataGridView1 对象所在的窗体的名称。

Can anyone please show me an easy method to fill a combobox in a datagridview in unbound mode.任何人都可以向我展示一种在未绑定模式下填充 datagridview 中的组合框的简单方法。 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您正在使用 GridViewComboBoxCell,而不是使用 GridViewComboBoxColumn 并参考下面给出的代码片段,这将正常工作

    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.上面的代码将为 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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