通过名称访问表单控件

3

我不确定这篇文章的标题是否准确。我正在尝试通过在循环中“组合”名称来访问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

我希望使用 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
作为额外的要求,我希望能够将最终的".Text"属性也作为字符串传递,在某些情况下需要"Text"属性的值,在其他情况下需要"Value"属性的值;总体而言,我感兴趣的属性可能是 i 的一个函数。 祝好。

注意:我已经尝试使用“Me.Controls(“label”&i)”,但对我无效!可能是因为标签嵌套在其他控件中(例如XtraTabControls中的XtraTabPages等等...)? - Andrea Aloi
1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
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
使用反射来设置通过字符串标识的属性的方法示例。
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)

最好避免隐藏错误。异常是一件好事。 - Hans Passant
太好了。现在如果我能通过名称(也作为字符串传递)访问控件的属性,那就太棒了。而不是像 ctrl(0).Text 这样的东西,应该是 ctrl(0).GetProperty("Text"),因为我想获取的属性取决于 i 的值(因此将是这种类型的东西:ctrl(0).GetProperty(f(i)),其中 f 返回一个字符串)。干杯。 - Andrea Aloi
谢谢 @Steve,我会查看它的。 - Andrea Aloi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,