如何在 vb .net 中刷新组合框项目
如果您正在谈论 WinForm 上的组合框,该组合框已使用数据源属性分配给对象列表,我发现您必须使数据源设置无效,并在每次列表更改时重新分配它。
即
attendanceDataFiles.DataSource = Nothing
attendanceDataFiles.DataSource = myFileList.files
attendanceDataFiles.DisplayMember = "displayName"
attendanceDataFiles.ValueMember = "fileName"
如果组合框的内容来自 MySql 数据库,这是刷新组合框项目的另一种方法。您可以在查询中自定义结果。
comboboxname.Items.clear() 'empty combo box content first
query = "select code, description from tbl_mode_of_payment where cat = 'LICENSE'" 'mysql query that retrieves payment code and its description based on category
cmd = New MySqlCommand(query, con)
reader = cmd.ExecuteReader()
While reader.Read
comboboxname.Items.Add(reader.GetString("code") + " - " + reader.GetString("description")) 'add results into the combo box
End While
con.Close()
Textbox1.Item.Clear() 然后 调用.item_tb()
在另一个表单将新项目添加到数据库表中后,我必须刷新组合框。我还为组合框使用数据源。这就是我所做的,效果很好。
Dim cmd As New OleDbCommand()
Dim dt_Institutions As DataTable
'~~ The connection is a public OleDbConnection at the head of the form class
cmd.Connection = conn
conn.Open()
'~~ The control already has been assigned a datasource. Instead of creating
' new one, I reuse the old one. It must first be cleared of the old data
dt_Institutions = cb_Institutions.DataSource
dt_Institutions.Clear()
cmd.CommandText = "SELECT Institutions.InstitutionID, " &
" Institutions.Institution " &
" FROM Institutions " &
" ORDER BY Institutions.Institution"
'~~ While this is not necessary, if you have a large amount of data beging
' filled in, the combobox control will want to sort and organize it with
' each add. This prevents that from happening (and speeding up the code)
dt_Institutions.BeginLoadData()
'~~ Looping through the data from the SELECT statement and filling up the
' the recycled dataset
Using rdr As OleDbDataReader = cmd.ExecuteReader()
While rdr.Read()
dt_Institutions.Rows.Add({rdr("InstitutionID"), rdr("Institution").ToString})
End While
End Using
'~~ Let the combobox take back over and organize itself only after all the
' data has been retrieved
dt_Institutions.EndLoadData()
cb_Institutions.SelectedIndex = -1
conn.Close()
我已将其与 MS-Access 数据库一起使用,并在 VS 2022 中进行编码。该过程是从添加了新记录(在本例中为新机构)的另一个表单中调用的。