如何在 VB.NET 中填充组合框

HOW TO FILL COMBO BOX IN VB.NET

我有一个代码来填充我的组合框,但每次我关闭表格时,列表都会加倍,如果我在关闭表格并再次打开后有来自我的英语、数学、科学数据库的列表显示的列表现在是英语,数学,科学,英语,数学,科学

这是代码,

    Call OpenDB()

    cmd.CommandText = "select * from Subject"
    cmd.Connection = conn
    dr = cmd.ExecuteReader

    While dr.Read()
        cmbSubject.Items.Add(dr("Subject Name"))    

    End While
    dr.Close()

    Call CloseDB()

问题不在于您用来绑定 combobox 的方法。每次绑定时,这就是为什么您在数据库中获得重复记录的原因。为避免这种情况,请在每次绑定之前清除 combobox,如下所示:

Call OpenDB()
cmbSubject.Items.Clear ' extra statement added to clear the item collection
cmd.CommandText = "select * from Subject"
cmd.Connection = conn
dr = cmd.ExecuteReader
While dr.Read()
    cmbSubject.Items.Add(dr("Subject_Name"))
End While
dr.Close()
Call CloseDB()

如果您需要另一种方法来绑定 combobox,我建议您使用 Dataset 进行绑定 以下是此示例代码:

    Dim  SQL As String= "select Subject_Name,Subject_code from Subject"
    Dim adapter As New OdbcDataAdapter(SQL, conn) '<-- This function will Retrieve Data and Return as Dataset together with table name
    Dim myData As New DataSet
    myData.Fill(lobjDataSet, tblName)
    cmbSubject.DataSource = ds_myData 
    cmbSubject.DataMember = "Subject"
    cmbSubject.DataTextField = "Subject_Name"
    cmbSubject.DataValueField = "Subject_code"
    cmbSubject.DataBind()
    myData .Dispose()
Public Class frmRegistration
    Dim obj As New Entity.Registration
    Dim bus As New Business.Registration



    Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        BindingSource1.EndEdit()
        bus.Save(obj)
        RefreshGrid()
        MsgBox("Saved.")
    End Sub


    Sub RefreshGrid()
        Dim dt1 As DataTable = bus.Select()
        BindingSource2.DataSource = dt1
        DataGridView1.AllowUserToAddRows = False
        DataGridView1.DataSource = BindingSource2
    End Sub

    Private Sub Registration_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        RefreshGrid()
        NewItem()
    End Sub

    Private Sub BtnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnNew.Click
        NewItem()
    End Sub

    Sub ResetDis()
        BindingSource1.DataSource = obj
    End Sub

    Sub NewItem()
        obj = New Entity.Registration
        ResetDis()
    End Sub


    Private Sub BindingSource2_CurrentChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BindingSource2.CurrentChanged
        obj = New Entity.Registration(CType(Me.BindingSource2.Current, DataRowView).Row)
        ResetDis()
    End Sub


End Class