如何设置组合框,始终使用相同的数据,作为在多个窗体上使用的用户控件



我有一个在多个WinForms上使用的组合框。与其在每个WinForm上删除一个组合框,然后用每个WinForm的DataTable中的数据填充组合框,难道我不能创建一个已经填充了数据的用户控件(组合框(,并在我的Winforms上使用该UC吗?

下面是我现在如何填写每个组合框的数据。(我有一个sql的公共类(

变量SQL来自一个名为SQLControl的类。该类具有所有sql连接内容。

Public Sub Fillcombobox()
sql.AddParam("@ExaminerType", 3)
sql.ExecQuery("MyStoredProcedure")
ComboBoxExaminer.ValueMember = "Examiner_ID"
ComboBoxExaminer.DisplayMember = "Last_Name"
ComboBoxExaminer.DataSource = sql.DBDT
End Sub
Private Sub MyWinform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call Fillcombobox()
End Sub

您可以放置一个小型Class Examiner

Public Class Examiner
Public Property Examiner_ID As Integer
Public Property Last_Name As String
Public Sub New(ID As Integer, lname As String)
Examiner_ID = ID
Last_Name = lname
End Sub
End Class

然后,当加载第一个表单时,获取模块中声明的列表中的数据,以便可以从应用程序中的任何表单访问该数据。当然,模块中可能还有其他内容。

Module Module1
Public ExaminerData As New List(Of Examiner)
End Module
Private Sub MyWinform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FillExaminerList()
ComboBoxExaminer.ValueMember = "Examiner_ID"
ComboBoxExaminer.DisplayMember = "Last_Name"
ComboBoxExaminer.DataSource = ExaminerData
End Sub

任何其他需要数据来填充组合框的表单都可以使用ExaminerData。在应用程序开始时只调用FillExaminerList一次。数据库中只有一个命中。

Private OPConStr As String = "Your connection string."
Private Sub FillExaminerList()
Dim dt As New DataTable
Using cn As New SqlConnection(OPConStr),
cmd As New SqlCommand("MyStoredProcedure", cn)
cmd.Parameters.Add("@ExaminerType", SqlDbType.Int).Value = 3
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
For Each row As DataRow In dt.Rows
Dim ex As New Examiner(CInt(row("Examiner_ID")), row("Last_Name").ToString)
ExaminerData.Add(ex)
Next
End Sub

最新更新