动态更改文本框值?

时间:2013-02-17 16:48:51

标签: vb.net variables dynamic

我有7个名为lblSun,lblMon等的文本框和7个名为cmdSun,cmdMon等的按钮。我想在查询中更改这些文本框和按钮的Text值。我试过了Me.Controls("cmd" & daysOfWeek(i)).Text,但它不起作用。

错误是对象引用未设置为对象的实例。

这是我的代码:

Public Sub loadSchedule()
    ' days of week
    Dim daysOfWeek(0 To 6) As String
    Dim i As Integer
    Dim var As String
    Dim ctrl As Control
    ' set up the days of the week
    daysOfWeek(0) = "Sun"
    daysOfWeek(1) = "Mon"
    daysOfWeek(2) = "Tue"
    daysOfWeek(3) = "Wed"
    daysOfWeek(4) = "Thu"
    daysOfWeek(5) = "Fri"
    daysOfWeek(6) = "Sat"
    ' connect to the db
    Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection(Form1.conString)
    con.Open()
    ' query stuff
    Dim query As String
    Dim cmd As New OleDb.OleDbCommand
    Dim rs As OleDb.OleDbDataReader
    ' loop
    For i = LBound(daysOfWeek) To UBound(daysOfWeek)
        ' set query
        query = "SELECT * FROM Schedule WHERE Employee=" & employee & " AND ScheduleDay='" & daysOfWeek(i) & "'"
        cmd = New OleDb.OleDbCommand(query, con)
        rs = cmd.ExecuteReader()
        ' var
        var = "cmd" & daysOfWeek(i)
        ' any results?
        If rs.HasRows = True Then
            ' get it
            rs.Read()
            ' show it baby
            'Controls("lbl" & daysOfWeek(i)).Text = rs.Item("TimeIn") & " - " & rs.Item("TimeOut")
            Me.Controls("cmd" & daysOfWeek(i) & "").Text = "Edit"
        Else
            ' show it baby
            Controls("lbl" & daysOfWeek(i)).Text = "RDO"
            Controls("cmd" & daysOfWeek(i)).Text = "New"
        End If
    Next
    ' close db
    con.Close()
End Sub

任何人都可以帮助我吗?我做错了什么?

1 个答案:

答案 0 :(得分:1)

您正尝试访问Me.Controls中不存在的控件,因为按钮/文本框位于表格内。

您应该使用:

table.Controls("cmd" & daysOfWeek(i)).Text = "Edit"