覆盖以前的组合框选择?

时间:2016-12-23 13:53:13

标签: vb.net winforms visual-studio combobox

我目前在表单中有两个ComboBox。 ComboBox A用于选择某个项目。 ComboBox B将填充4个特定于ComboBox A中所做选择的项目。我能够完成所有这些工作。

我的问题是:如果我在ComboBox A中进行选择,ComboBox B将填充特定于我在ComboBox A中所做选择的4个项目。但是如果我在ComboBox A中进行另一个选择,则项目不会覆盖以前在ComboBox B中填充的项目,它们只是添加到已填充的项目中。

我的问题是,当在ComboBox A中进行新选择时,有没有在ComboBox B中覆盖以前的项目?

Imports MySql.Data.MySqlClient
Public Class Form2
Dim MySqlConn As MySqlConnection
Dim COMMAND As MySqlCommand
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    MySqlConn = New MySqlConnection
    MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=test"
    Dim READER As MySqlDataReader
    Try
        MySqlConn.Open()
        Dim Query As String
        Query = "select * from test.boxinformation"
        COMMAND = New MySqlCommand(Query, MySqlConn)
        READER = COMMAND.ExecuteReader
        While READER.Read
            Dim boxSN = READER.GetString("Box_SN")
            ComboBox_Box.Items.Add(boxSN)
        End While
        MySqlConn.Close()
    Catch ex As MySqlException
        MessageBox.Show(ex.Message)
    Finally
        MySqlConn.Dispose()
    End Try
End Sub
Private Sub ComboBox_STSBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox_Box.SelectedIndexChanged
    MySqlConn = New MySqlConnection
    MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=test"
    Dim READER As MySqlDataReader
    Try
        MySqlConn.Open()
        Dim Query As String
        Query = "select * from test.boxinformation where Box_SN='" & ComboBox_Box.Text & "'"
        COMMAND = New MySqlCommand(Query, MySqlConn)
        READER = COMMAND.ExecuteReader
        While READER.Read
            ComboBox_Port.Items.Add(READER.GetString("1_IP"))
            ComboBox_Port.Items.Add(READER.GetString("2_IP"))
            ComboBox_Port.Items.Add(READER.GetString("3_IP"))
            ComboBox_Port.Items.Add(READER.GetString("4_IP"))
        End While
        MySqlConn.Close()
    Catch ex As MySqlException
        MessageBox.Show(ex.Message)
    Finally
        MySqlConn.Dispose()
    End Try
End Sub

结束班

2 个答案:

答案 0 :(得分:0)

如果您添加新项目而不先删除旧项目,那么这将是预期的行为。要在添加新集合之前从组合框中删除所有项目,您需要清除其objectCollection,如下所示;

ComboBoxA.ObjectCollection.Clear()
'now add your new set of items...

答案 1 :(得分:0)

为了让你以前的值使用ComboBox_Port.Clear的ComboBox,把它放在你的行之后

READER = COMMAND.ExecuteReader

所以你的代码将是:

READER = COMMAND.ExecuteReader
' *** drop your new line here ***
ComboBox_Port.Clear
While READER.Read
    ComboBox_Port.Items.Add(READER.GetString("1_IP"))
    ComboBox_Port.Items.Add(READER.GetString("2_IP"))
    ComboBox_Port.Items.Add(READER.GetString("3_IP"))
    ComboBox_Port.Items.Add(READER.GetString("4_IP"))
End While