基于数据表设置DataGridViewComboBoxColumn值

时间:2016-08-08 12:15:41

标签: vb.net datagridview combobox datagridviewcolumn

我读了几篇关于设置组合框值的文章但是我仍然无法提出解决方案。

以下是我想要做的基本示例,在评论中正是我想要做的。任何帮助表示赞赏。

  Public Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim dt As New DataTable
    dt.Columns.Add("ID")
    dt.Columns.Add("Name")
    dt.Columns.Add("Value")
    dt.Columns(0).AutoIncrement = True

    For i As Integer = 0 To 20
        Dim R As DataRow = dt.NewRow
        R("Name") = "Test" & Date.Now & "" & i
        If i = 2 Or i = 5 Or i = 6 Or i = 8 Or i = 10 Then
            R("Value") = "yes"
        Else
            R("Value") = "no"
        End If
        dt.Rows.Add(R)
        DataGridView1.DataSource = dt
    Next

    DataGridView1.ReadOnly = False

    Dim cmb As New DataGridViewComboBoxColumn()
    cmb.HeaderText = "Select Data"
    cmb.Name = "cmb"
    cmb.MaxDropDownItems = 2
    cmb.Items.Add("True")
    cmb.Items.Add("False")
    DataGridView1.Columns.Add(cmb)

    For Each dr As DataRow In dt.Rows
        If dr("Name").ToString = "Test" Then
            'set the combo box value to True
        Else
            'set the combobox value to False
        End If
    Next

End Sub

1 个答案:

答案 0 :(得分:1)

您可以通过设置value ...

来设置Cells.Value
 DataGridView1.Rows(whatrowdoyouwant).Cells("cmb").Value = True 

另一方面,您将DataSource设置为DataGridView,但循环显示DataTable。如果你想设置DataGridView中的每一行都不行。

 For Each dr As DataRow In dt.Rows
    If dr("Name").ToString = "Test" Then
        'set the combo box value to True
    Else
        'set the combobox value to False
    End If
 Next

您需要遍历DataGridViewRow中的每个DataGridView并设置ComboBox值。例如......

 For i As Integer = 0 To DataGridView1.Rows.Count - 1
    If DataGridView1.Rows(i).Cells("Name").Value.ToString = "Test" Then
        DataGridView1.Rows(i).Cells("cmb").Value = True 
    Else
        DataGridView1.Rows(i).Cells("cmb").Value = False
    End If
 Next