我有一個用于多個 WinForm 的 ComboBox。與其在每個 WinForm 上放置一個 ComboBox,然后用每個 WinForm 上的 DataTable 中的資料填充 ComboBox,我不能創建一個已經填充資料的用戶控制元件 (ComboBox),然后在我的 Winform 上使用該 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
uj5u.com熱心網友回復:
你可以放一個小 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/365589.html
下一篇:winforms識別符號不可見
