嘿,每个人都可以帮助我使用vb.net中的一些代码
我创建了一个可以使用OleDbDataReader生成标签的循环 现在我想知道我是否可以让这些标签开启新形式 我可以在我的新表单中使用此标签中的数据,如创建的标签文本! 这是我的代码:
Dim cnn As New OleDbCommand(query, con)
Dim cmd As New OleDbDataAdapter(cnn)
Dim dt As New DataTable()
cmd.Fill(dt)
Dim reader As OleDbDataReader
reader = cnn.ExecuteReader()
Dim number As Integer = 0
Dim location As Integer = 0
While reader.Read()
Dim sensibleFont As New Font("Segoe UI", 15)
Dim lb As New Label()
lb.Name = "labb" + number.ToString
lb.Size = New System.Drawing.Size(350, 40)
lb.Location = New System.Drawing.Point(50, 15 + location)
lb.Text = dt.Rows(number)(0).ToString()
lb.ForeColor = Color.Black
lb.Font = sensibleFont
GroupBox1.Controls.Add(lb)
Dim lb2 As New Label()
lb2.Name = "labs" + number.ToString
lb2.Size = New System.Drawing.Size(280, 40)
lb2.Location = New System.Drawing.Point(10, 5 + location)
lb2.Text = dt.Rows(number)(2).ToString()
lb2.ForeColor = Color.Black
lb2.Font = sensibleFont
GroupBox2.Controls.Add(lb2)
location += 40
number += 1
End While
con.Close()
答案 0 :(得分:0)
创建一个符合您需要的子。
Private Sub OpenForm()
Dim myForm As New MyForm()
myForm.Show()
End Sub
在标签创建过程中,添加一个使用此子作为其处理程序的点击事件
AddHandler lb.Click, AddressOf OpenForm
答案 1 :(得分:0)
如A Friend的回答所示,您可以为标签的点击事件添加处理程序。扩展它以使用处理程序的正确签名,您可以获取引发事件的对象,并因此使用其属性,例如.Text
属性:
Sub Label_Click(sender As Object, e As EventArgs)
Dim lbl = DirectCast(sender, Label)
Dim frm2 = New OtherForm(lbl.Text)
frm2.Show()
End Sub
要使用它,你将需要另一种形式的构造函数(Sub New
)(我将其命名为#34; OtherForm"),如下所示:
Public Class OtherForm
Sub New()
InitializeComponent()
End Sub
Sub New(info As String)
InitializeComponent()
Label1.Text = info
End Sub
End Class
Label1
只是OtherForm
用于测试目的的标签。
您可能会发现控件的.Tag
属性更适合传递数据,因为它可以是任何对象,例如一个类的实例。
我注意到您正在读取数据库两次:一次填充数据表,然后再次作为数据表中行的计数,这有点浪费。此外,您应该在完成后处置字体:Using构造将为您处理,类似于连接到数据库。像这样:
Sub PopulateGroupBox()
Dim connStr = "CONNECTION STRING HERE"
Dim query = "SQL QUERY HERE"
Dim dt As New DataTable()
Using con As New OleDbConnection(connStr)
Dim cnn As New OleDbCommand(query, con)
Dim cmd As New OleDbDataAdapter(cnn)
cmd.Fill(dt)
End Using
Dim location As Integer = 0
Using sensibleFont As New Font("Segoe UI", 15)
For i = 0 To dt.Rows.Count - 1
Dim lb1 As New Label()
lb1.Name = "labb" & i.ToString()
lb1.Size = New System.Drawing.Size(350, 40)
lb1.Location = New System.Drawing.Point(50, 15 + location)
lb1.Text = dt.Rows(i)(0).ToString()
lb1.ForeColor = Color.Black
lb1.Font = sensibleFont
AddHandler lb1.Click, AddressOf Label_Click
GroupBox1.Controls.Add(lb1)
Dim lb2 As New Label()
lb2.Name = "labs" & i.ToString()
lb2.Size = New System.Drawing.Size(280, 40)
lb2.Location = New System.Drawing.Point(10, 5 + location)
lb2.Text = dt.Rows(i)(2).ToString()
lb2.ForeColor = Color.Black
lb2.Font = sensibleFont
AddHandler lb2.Click, AddressOf Label_Click
GroupBox2.Controls.Add(lb2)
location += 40
Next
End Using
End Sub