好的,我现在已经搜索了5天,找不到我要找的东西。
我的主表单上有21个按钮。名称结构是btn_Cat1 - btn_cat21 这是我的代码到目前为止,但这只做一个按钮。我需要做一个“do while”或某种循环来改变每个按钮上的文字。
Private Sub frm_MainConsole_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Procedures
Me.Show()
dbconn()
' Variables
Dim query As String
Dim command As MySqlCommand
Dim reader As MySqlDataReader
' creates the button text
Try
query = "select btn_caption from button_cat"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader()
reader.Read()
btn_Cat1.Text = reader("btn_caption")
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Close()
conn.Dispose()
End Try
End Sub
我真正遇到的问题是代码中的按钮命名。 IE:
dim i as integer
'this is what i would have done in pascal to advance the button name to the next button:
while i < 21 do
btn_Cat(i).text = "new button text from Database";
i = i+1;
'advance database record to next record
答案 0 :(得分:0)
您可以使用表单的Controls
集合来实现此目的 - 通过Key
找到每个按钮。
以下示例应该让您了解如何实现这一目标:
// For button 1 through 21
For i As Integer = 1 To 21 Step 1
Dim TargetButton As Button
// Get the button from the controls container
TargetButton = Controls("btn_Cat" & i)
TargetButton.Text = reader("btn_caption")
Next
您需要实现代码以从数据库中获取实际名称,但这应该可以帮助您入门。
从TryCast
容器中获取控件时,您可能希望使用Controls
,然后进行测试以确保实际返回该按钮。