如何循环访问21个按钮标题的数据库

时间:2016-09-02 03:00:58

标签: mysql vb.net

好的我再次敲击键盘。到目前为止,在这里有帮助表单,我确实得到了我的mysql查询来读取我想要的一个字段。但我的问题是:

概念。表格包含按钮数据,如标题,以及后者的其他内容。就像TAB一样,按钮会在点击时激活。 < - 后者现在并不重要,因为一旦我弄清楚这一部分,我问我能否轻易搞清楚我确定。所以。我有21个按钮。每个按钮都需要一个位于数据库中的标题。我想弄清楚的是如何遍历数据库以获取按钮1,然后按钮2的标题,依此类推。现在它正在为所有21个按钮加载相同的标题。这是我的代码:

Private Sub frm_MainConsole_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'TODO: This line of code loads data into the 'PosdbDataSet.button_cat' table. You can move, or remove it, as needed.
    Me.Button_catTableAdapter.Fill(Me.PosdbDataSet.button_cat)

    'Procedures
    Me.Show()
    ' Variables

    Dim query As String
    Dim command As MySqlCommand
    Dim reader As MySqlDataReader
    Dim TargetButton As Button

    Try
        'For button 1 through 21
        dbconn()
        For i As Integer = 1 To 21 Step 1
            query = "select btn_caption from button_cat"
            command = New MySqlCommand(query, conn)
            reader = command.ExecuteReader()
            reader.Read()
            'btn_Cat1.Text = reader("btn_caption")
            'Get the button from the controls container
            TargetButton = Controls("btn_Cat" & i)
            TargetButton.Text = reader("btn_caption")
            reader.Close()
        Next
        conn.Close()
    Catch ex As MySqlException
        MessageBox.Show(ex.Message)
    Finally
        conn.Dispose()
    End Try


End Sub

我感谢你能给我的任何帮助。我通过查看代码并操纵它来完成我需要它做的事情来学习。

我使用visual studio 2015社区和MySQL作为我的数据库并使用Visual Basic进行编写。

1 个答案:

答案 0 :(得分:2)

您在每个循环周期中重新运行查询。

做这样的事情:

    ''For button 1 through 21
    dbconn()

    query = "select btn_caption from button_cat"
    command = New MySqlCommand(query, conn)
    reader = command.ExecuteReader()

    For i As Integer = 1 To 21 Step 1

        reader.Read()
        ''btn_Cat1.Text = reader("btn_caption")
        ''Get the button from the controls container
        TargetButton = Controls("btn_Cat" & i)
        TargetButton.Text = reader("btn_caption")

    Next
    reader.Close()
    conn.Close()

请记住,此代码可能存在问题,因为它假定数据库总会返回21个结果。

如果要在返回的记录少于21条时防止出现问题,可以执行以下操作:

    ''For button 1 through 21
    dbconn()

    query = "select btn_caption from button_cat"
    command = New MySqlCommand(query, conn)
    reader = command.ExecuteReader()

    For i As Integer = 1 To 21 Step 1

         If Not reader.Read() Then
             ''We are out of records. Exit the loop.
             Exit For
         End If

        ''btn_Cat1.Text = reader("btn_caption")
        ''Get the button from the controls container
        TargetButton = Controls("btn_Cat" & i)
        TargetButton.Text = reader("btn_caption")

    Next
    reader.Close()
    conn.Close()

您也可以将其重写为while循环,但您需要重新实现i计数器。