简体   繁体   English

为什么我不能引用文本框名称 vb.net

[英]Why I can't reference textbox name vb.net

I want to add value from array to each textbox.我想将数组中的值添加到每个文本框。
Here is my code:这是我的代码:

For i as int32 = 0 To Array.length - 1
    Me.Controls("TextBox" & i + 1).Text = Array(i)
Next

When I run above code, I got the NullReferenceException error.当我运行上面的代码时,我收到了 NullReferenceException 错误。
Error Line is:错误行是:

Me.Controls("TextBox" & i + 1).Text = Array(i) Me.Controls("TextBox" & i + 1).Text = Array(i)

I tried another code after searching from the web,我从网上搜索后尝试了另一个代码,

For i as int32 = 0 To Array.length - 1
    Dim c as Control() = Me.Controls.Find("TextBox" & i + 1 , True)
    If c.Length = 1 Then
        Me.Controls("TextBox" & i + 1).Text = Array(i)
    End If
Next

But it still doesn't work.但它仍然不起作用。 Please help me... Thanks in advanced.请帮帮我...先谢谢了。

Find can return Null (nothing) if it doesn't find a result, which is causing your null reference exception.如果 Find 没有找到结果,则它可以返回 Null(无),这会导致您的空引用异常。

As for enumerating/looping over your textbox controls:至于枚举/循环你的文本框控件:

Try explicitly looping over them using a foreach on your controls collection尝试在控件集合上使用 foreach 显式循环它们

    For Each control In Me.Controls
        If control.GetType() Is GetType(TextBox) Then
            'Do stuff to control.
        End If
    Next

The process you're using now of attempting to map to the name of the control is not going to be very adaptable, especially if someone else comes a long and changes the name of the control.您现在使用的尝试映射到控件名称的过程将不会具有很强的适应性,特别是如果其他人来了很长时间并更改了控件的名称。

If there are only a certain set of textboxes you want to update, you could put them in a panel on the form, and use the same method described above to loop through the panel's controls.如果您只想更新一组特定的文本框,您可以将它们放在表单的面板中,并使用上述相同的方法循环浏览面板的控件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM