如何在vb.net中控制控件名中的变量整数

时间:2013-08-15 08:34:00

标签: vb.net winforms visual-studio-2012 for-loop user-controls

现在我有一个数据库并提取数据并将其显示为表格,我有一系列的groupbox和radiobuttons,在每个groupbox(groupbox1,groupbox2等等)中有2个单选按钮,即rdbtn1Yes和rdbtn1No (然后在下一个Groupbox中增加+1)。现在我使用for loop遍历每个组框和单选按钮。这是我的代码:

    Dim sqlda As New SqlDataAdapter("SELECT * FROM table1 WHERE column1= '" & lblWONo.Text & "'", Constr)
    Dim sqlds As New DataSet

    sqlds.Clear()
    sqlda.Fill(sqlds)

    If sqlds.Tables(0).Rows.Count > 0 Then

        With sqlds.Tables(0).DefaultView.Item(0)

            txtDateCreated.Value = .Item(0).ToString
            txtComments.Text = .Item(1).ToString

            'check column if it contain FALSE/TRUE value
            'then toggle the radiobutton state to TRUE

            'In this part i know there is another/easiest way to checked radio buttons to TRUE value 
            'and this is my code using looping (below):

            If .Item(2) = False Then
                rdbtn1No.Checked = True
            Else
                rdbtn1Yes.Checked = True
            End If

            If .Item(3) = False Then
                rdbtn2No.Checked = True
            Else
                rdbtn2Yes.Checked = True
            End If

            If .Item(4) = False Then
                opt3N.Checked = True
            Else
                opt3Y.Checked = True
            End If
        End With
    End If

循环示例代码:

            Dim itemNo As Integer
            Dim rdbtnSet As Integer = 1
            Dim grpboxCnt As Integer = 1

             For Each grpbx As GroupBox In Me.Controls.OfType(Of GroupBox)()
                For itemNo = 2 To sqlds.Tables(0).Columns.Count

                    If .Item(itemNo) = True Then
                        rdbtn & rdbtnSet & "Yes".checked = True 'I want to be this way but we know that this is not working or its not the proper way. That is my problem.
                    Else 
                        rdbtn & rdbtnSet & "No".checked = True 'I want to be this way but we know that this is not working or its not the proper way. That is my problem.
                    End If

                Next
                 rdbtnSet += 1
                 grpboxCnt += 1
             Next

多数民众赞成。先感谢您!

1 个答案:

答案 0 :(得分:1)

考虑使用字典(id,control)来存储控件。然后迭代字典并设置你的状态。