Access a form's control by name

时光毁灭记忆、已成空白 提交于 2021-02-07 22:46:19

问题


not sure whether the title of this post is accurate. I'm trying to access windows form controls and their properties by "composing" their name within a loop, but I can't seem to find the related documentation. Using VB.net. Basically, say I have the following:

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

I'd like to write a for loop instead of N separate instructions. While it's simple enough to express the left-hand side of the assignments, I'm stumped when it comes to the right-hand side:

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

As an extra, I'd like to be able to pass the final ".Text" property as a string as well, for in some cases I need the value of the "Text" property, in other cases the value of the "Value" property; generally speaking, the property I'm interested in might be a function of i.

Cheers.


回答1:


You could use the ControlsCollection.Find method with the searchAllChildren option set to 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

An example on how to approach the problem using reflection to set a property that you identify using a string

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)


来源:https://stackoverflow.com/questions/24164039/access-a-forms-control-by-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!