如何在运行时使用组合框在“ DATAGRIDVIEW”中添加列表

时间:2020-05-18 21:12:08

标签: vb.net winforms visual-studio-2019

我尝试了以下代码,但是每次开始新行时都会添加列表,因此如果我们有两行,则将其添加两次;如果移到三行,则将列表添加三倍

请向我提供简单明了的方法,以将列表添加到datagridview的组合框中

    Dim CON As New MySqlConnection("server=localhost; username=root; password=Masoom1; database=airtech_db;")
    Dim cmd As New MySqlCommand("Select * from `Suppliers`;", CON)
    Dim da As New MySqlDataAdapter("Select * from `Suppliers`;", CON)
    Dim ds As New DataSet
    Dim dr As MySqlDataReader
    Dim TOTAL_SUPPLIERS As Integer



    CON.Open()
    da.Fill(ds)
    dr = cmd.ExecuteReader
    TOTAL_SUPPLIERS = ds.Tables(0).Rows.Count
    Dim TOTAL_SUPPLIERS_ARRAY(TOTAL_SUPPLIERS) As String, ARRAYINDEX As Integer
    ARRAYINDEX = 0
    Do While dr.Read() = True
        TOTAL_SUPPLIERS_ARRAY(ARRAYINDEX) = dr("Supplier_Name").ToString()
        ARRAYINDEX += 1
    Loop
    CON.Close()


    Dim cbCell As New DataGridViewComboBoxCell
    For k = 0 To DataGridView1.Rows.Count - 1
        cbCell = DataGridView1.Rows(k).Cells("Supplier_Name")
        For iIndex = 0 To UBound(TOTAL_SUPPLIERS_ARRAY) - 1
            cbCell.Items.Add(TOTAL_SUPPLIERS_ARRAY(iIndex))
        Next

    Next

2 个答案:

答案 0 :(得分:0)

好吧,我找到了一种解决现有问题的简单方法,可以解决此问题,因为每次运行时,它都会清除现有列表,并让列表再次添加,因此将cbCell.Items.Clear()添加到代码帮助中

 Dim cbCell As New DataGridViewComboBoxCell
    For k = 0 To DataGridView1.Rows.Count - 1
        cbCell = DataGridView1.Rows(k).Cells("Supplier_Name")
        cbCell.Items.Clear()

        For iIndex = 0 To UBound(TOTAL_SUPPLIERS_ARRAY)
            cbCell.Items.Add(TOTAL_SUPPLIERS_ARRAY(iIndex))
        Next
    Next

答案 1 :(得分:0)

您只能为列设置一次。

例如,您可以在加载表单时填充组合框。

Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyForm.Load
    With Me.DataGridView.Columns("Supplier_Name")
       .DataSource = GetSupplierNames()
    End With
End Sub

Private Function GetSupplierNames() As List(Of String)
    Dim query As String = "SELECT Supplier_Name FROM Suppliers"

    Using connection As New MySqlConnection(connectionString)
        Using command As New MySqlCommand(query, connection)
            connection.Open()
            Dim supplierNames = new List(Of String)()

            Using reader AS MySqlDataReader = command.ExecuteReader()
                While reader.Read()
                    Dim name As String = reader.GetString(0)
                    supplierNames.Add(name)
                End While
            End Using

            Return supplierNames
        End Using
    End Using
End Function