在 VB 中使用控件更改标签文本 [英] Change Label Text with Controls in VB

查看:95
本文介绍了在 VB 中使用控件更改标签文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此行更改带有控件命令的标签文本

I'm trying to change a Label Text with Controls command, using this line

Controls("C_" & 0).Text = "Conta:"

但我收到此错误

System.NullReferenceException"

"System.NullReferenceException"

如果我删除此标签并将其更改为文本框(具有相同名称C_0"),它会起作用!但是我需要使用标签而不是文本框来执行此操作...

If I delete this label and change it for a textbox (with same name "C_0"), it works! But I need to do this with a Label not a textbox...

推荐答案

这是因为您没有名为 C_0 的控件.我建议使用 ControlCollection.Find 获取您的控件,然后使用条件 If 语句检查返回的控件是否存在:

This is because you do not have a control named C_0. I would suggest using ControlCollection.Find to get your control and then use a conditional If statement to check if the returned control exists:

Dim desiredControls() As Control = Me.Controls.Find("C_" & 0, True)
If desiredControls.Count = 0 Then
    'No controls named C_0 found
ElseIf desiredControls.Count > 1 Then
    'Multiple controls named C_0 found
Else
    desiredControls(0).Text = "Conta:"
End If

或者,如果您只是想要一个单线,那么您可以使用:

Or if you simply wanted a one-liner then you would use:

Me.Controls.Find("C_" & 0, True).First().Text = "Conta:"

但是,我强烈建议您使用条件 If 语句,以便在找到 0 个控件时不会引发异常.

However, I would highly recommend that you use the conditional If statements so that you an exception isn't thrown if 0 controls are found.

这篇关于在 VB 中使用控件更改标签文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆