如何循环遍历具有顺序控件名称的systems.windows.forms.controls?

时间:2016-01-14 19:54:56

标签: vb.net

我有按顺序命名的单选按钮,例如" Jbtn1'到" Jbtn20"。我试图通过使用for循环使用set toolTip来命名这些按钮。

 Dim toolTip1 As New ToolTip()
 For j As Integer = 1 To 20
   Dim pinInfo As String = "J2-" & j
   'Tried to convert the buttonName as Control , but got an error as 
   'Value of string cannot be converted to systems.windows.forms.control 
   Dim buttonName As Control = "Jbtn" & j
   toolTip1.SetToolTip(buttonName, pinInfo)
 Next

任何建议都表示赞赏。

2 个答案:

答案 0 :(得分:2)

您可以这样做:

Dim toolTip1 As New ToolTip()
For j As Integer = 1 To 20
    Dim pinInfo As String = "J2-" & j
    Dim control As Control = Me.Controls.Item("Jbtn" & j)
    toolTip1.SetToolTip(control, pinInfo)
Next

此代码使用表单的Controls属性来访问表单上的控件。您可以使用Controls上的索引器按名称查找单个控件。

答案 1 :(得分:0)

我会考虑动态创建和添加按钮,而不是依赖于硬编码名称。

也就是说,您可以使用ControlCollection(controlNameString)按名称查找它们。

您还可以使用LINQ to Objects:

    /* Dropdown Button */
.dropbtn {
    background-color: Transparent;
    background-repeat:no-repeat;
    border: none;

    cursor:pointer;
    overflow: hidden;
    outline:none;
    text-shadow:none !important;
    box-shadow:none !important;



}

/* The container <div> - needed to position the dropdown content */
.dropdown {
    position: relative;
    display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

/* Links inside the dropdown */
.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #f1f1f1}

/* Show the dropdown menu on hover */
.dropdown:hover .dropdown-content {
    display: block;
}

/* Change the background color of the dropdown button when the dropdown content is shown */
.dropdown:hover {
    background-color: #3e8e41;
}

.dropbtn:hover
{
  text-color: black;
}