通过名称访问表单的控件

And*_*loi 3 vb.net winforms

不确定这篇文章的标题是否准确。我试图通过在循环中“组合”它们的名称来访问 Windows 窗体控件及其属性,但我似乎找不到相关文档。使用VB.net。基本上,假设我有以下内容:

Dim myDt As New DataTable

Dim row As DataRow = myDt.NewRow()

row.Item("col01") = Me.label01.Text
row.Item("col02") = Me.label02.Text
'...
row.Item("colN") = Me.labelN.Text
Run Code Online (Sandbox Code Playgroud)

我想编写一个 for 循环而不是 N 个单独的指令。虽然表达作业的左侧很简单,但当涉及到右侧时,我却被难住了:

For i As Integer = 1 to N
    row.Item(String.format("col{0:00}", i)) = ???
    ' ??? <- write "label" & i (zero-padded, like col) and use that string to access Me's control that has such name
Next
Run Code Online (Sandbox Code Playgroud)

另外,我希望能够将最终的“.Text”属性作为字符串传递,因为在某些情况下我需要“Text”属性的值,在其他情况下需要“Value”的值“ 财产; 一般来说,我感兴趣的属性可能是 i 的函数。

干杯。

Ste*_*eve 5

您可以使用ControlsCollection.Find方法并将searchAllChildren选项设置为 true

For i As Integer = 1 to N
    Dim ctrl = Me.Controls.Find(string.Format("label{0:00}", i), True)
    if ctrl IsNot Nothing AndAlso ctrl.Length > 0 Then
        row.Item(String.format("col{0:00}", i)) = ctrl(0).Text
    End If
Next
Run Code Online (Sandbox Code Playgroud)

有关如何使用反射来设置您使用字符串标识的属性来解决问题的示例

Dim myLabel As Label = new Label()
Dim prop as PropertyInfo = myLabel.GetType().GetProperty("Text")
prop.SetValue(myLabel, "A Label.Text set with Reflection classes", Nothing)
Dim newText = prop.GetValue(myLabel)
Console.WriteLine(newText)
Run Code Online (Sandbox Code Playgroud)