For循环到更改按钮的颜色取决于数据库中的数据

时间:2017-11-03 17:41:10

标签: vb.net winforms

我想更改按钮的背景颜色取决于来自数据库的信息, 我的表格有多个按钮,如图所示。

我有一个商店(商店)的数据库表,此表中有一列包含商店编号及其状态列:(如果租用或为空)

表单形状中的

每个商店都有一个按钮,此按钮被命名为数据库中商店编号的编号 如何循环从数据库中检索商店数据 并更改按钮的颜色取决于数据库中的数据(如果它是空的或租用的)。

这是我尝试的但是我收到了这个错误:

对象引用未设置为对象的实例。 (关于改变颜色代码) - > btn.BackColor = Color.LightPink

这是我的代码:

    Dim pagingAdapter As SqlDataAdapter
    Dim pagingDS As DataSet
    Dim dt As New DataTable

    Dim sqlstring As String = "Select * FROM shops where location='G2'"

    If SQL.conn.State = ConnectionState.Open Then
        SQL.conn.Close()
    End If
    SQL.conn.Open()

    pagingAdapter = New SqlDataAdapter(sqlstring, SQL.conn)
    pagingDS = New DataSet()
    pagingAdapter.Fill(pagingDS, "shops")
    dt = pagingDS.Tables("shops")
    MsgBox(dt.Rows.Count)

    For Each row As DataRow In dt.Rows
        Dim id As Integer = row("shop_id")
        Dim state As String = row("status")
        Dim btn As Button = TryCast(Me.Controls("Button" & id), Button)

        If state = "rented" Then
            btn.BackColor = Color.LightPink
        ElseIf state = "empty" Then
            btn.BackColor = Color.LightGreen
        End If
    Next
    SQL.conn.Close()

这是形式,我有5个不同的形状 enter image description here

0 个答案:

没有答案