在非绑定模式下以编程方式填充DataGridView ComboBox吗? [英] Filling DataGridView ComboBox programatically in unbound mode?

查看:54
本文介绍了在非绑定模式下以编程方式填充DataGridView ComboBox吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码段(问题在这里: http://www.vbdotnetforums.com/winforms-grids/10038-fill-datagridview-combobox-column.html )用于以未绑定模式在datagridview中填充组合框单元格:

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")

我正在尝试这样做也一样,但是我不禁注意到强制转换操作无效,这就是VB给我的确切错误。

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 是DataGridView1对象所在的表单的名称。

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

谁能告诉我一种简单的方法来以非绑定模式在datagridview中填充组合框。您还可以告诉我为什么它对我不起作用以及为什么对其他人有用?

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?

推荐答案

GridViewComboBoxCell,取而代之的是GridViewComboBoxColumn并参考下面给出的代码片段,该代码片段可以正常工作

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")

上面的代码将为DataGridview提供如下结果。

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

编辑:

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

这篇关于在非绑定模式下以编程方式填充DataGridView ComboBox吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆