【问题标题】:How can I write a loop to replace this if statement for different buttons如何编写循环来替换不同按钮的 if 语句
【发布时间】:2018-10-31 19:31:14
【问题描述】:

我有一个名为 A 的 Access 数据表。它有 90 行,每行有 2 列,如下所示:

我有一个有 90 个绿色按钮和代码的 vb 表单:

Private Sub _1st_Floor_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim myConnection As New OleDbConnection(myConnString)
    Dim myCommand As New OleDbCommand("SELECT ID FROM A WHERE Busy=True", myConnection)
    myConnection.Open()
    Dim reader As OleDbDataReader
    Dim dt As New DataTable
    dt.Load(myCommand.ExecuteReader)
    If dt.Rows(0).Item(0).ToString = 1 Then
        Button1.BackColor = Color.Red
        Button1.FlatAppearance.BorderColor = Color.Red
    End If
    If dt.Rows(1).Item(0).ToString = 2 Then
        Button2.BackColor = Color.Red
        Button2.FlatAppearance.BorderColor = Color.Red
    End If
End Sub

这很好用,但我不想为 90 个按钮一遍又一遍地重复相同的 If 块。如何用一组代码为所有 90 个按钮编写一个循环?

【问题讨论】:

  • 表单上是否还有其他任何类型的按钮?按钮是否有一些公共容器,例如 GroupBox 或 Panel?按钮是否有一个通用的命名约定,可用于将它们与可能在范围内的其他按钮区分开来?
  • 按钮命名为 Button1 Button2 Button3 并且表单上还有其他按钮用于执行其他操作
  • 而且 Button1 有文本“1” button2 有文本“2”,所以没有容器或分组框
  • 那么第一步就是解决这个问题。您需要一些可以将按钮分开的东西,因此您可以在代码中将它们作为一个组引用。

标签: vb.net winforms ms-access


【解决方案1】:

遍历您的记录并找到相应的按钮:

For Each row As DataRow In dt.Rows
  Dim buttonName as String = "button" & row(0).ToString()
  Dim cntrls() As Control = Me.Controls.Find(buttonName, True)
  If cntrls IsNot Nothing Then
    Dim btn As Button = TryCast(cntrls(0), Button)
    If btn IsNot Nothing Then
      btn.BackColor = Color.Red
      btn.FlatAppearance.BorderColor = Color.Red
    End If
  End If
Next

这取决于按钮的命名方案是否一致。

【讨论】:

    【解决方案2】:

    使用你自己的“单词”:) 可能不是最有效的方法,但我只是想通过尽可能多地重用你的代码来编写这个......

    Private Sub _1st_Floor_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        Dim myConnection As New OleDbConnection(myConnString)
        Dim myCommand As New OleDbCommand("SELECT ID FROM A WHERE Busy=True", myConnection)
        myConnection.Open()
        Dim reader As OleDbDataReader
        Dim dt As New DataTable
        dt.Load(myCommand.ExecuteReader)
    
        For index As Integer = 1 To 90
            If dt.Rows(index - 1).Item(0).ToString = index.ToString Then
                Dim button As Button = CType(Me.Controls("Button" + index.ToString), Button)
                button.BackColor = Color.Red
                button.FlatAppearance.BorderColor = Color.Red
            End If
        Next
    
    End Sub
    

    我用这个post 来按名称获取控件String

    【讨论】:

      猜你喜欢
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 2019-06-10
      • 2010-10-05
      • 1970-01-01
      • 2023-03-16
      • 2021-09-20
      • 1970-01-01
      相关资源
      最近更新 更多