如何以正确的方式编写此代码?
Public Class Form1
Dim y As String = lbl_1.Text
它说:
{A first chance exception of type 'System.NullReferenceException' occurred in calculator.exe}
你能帮帮我们吗?
这是代码中的示例
Public Class Form1
Dim y As String = lbl_1.Text
Private Sub btn_diff_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_diff.Click
lbl_1.Text = y & "-*"
End Sub
Private Sub btn_1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_1.Click
lbl_1.Text = y & "1"
End Sub
Private Sub lbl_1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lbl_1.Click
Dim y As String = lbl_1.Text
lbl_1.Text = y
End Sub
Private Sub btn_n_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_n.Click
lbl_1.Text = ""
lbl_1.Focus()
End Sub
Private Sub btn_2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_2.Click
Dim y As String = lbl_1.Text
lbl_1.Text = y & "2"
End Sub
Private Sub btn_equal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_equal.Click
lbl_1.Text = Val(lbl_1.Text)
End Sub
结束班
我想制作一个计算器
但是我应该在最后一个按钮(btn_equal)中写什么?我已经尝试了val,但它不能正常工作
当我在每个控制器中声明y时它起作用但是在puplic中它不起作用
答案 0 :(得分:4)
Form1类中的控件需要在使用前初始化。如果要以这种方式使用控件,则需要将无参数构造函数显式添加到Form1类
Public Class Form1
Dim y as String
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
y = lbl_1.Text
....
End Sub
End Class
在您的实际代码中,标签控件文本的读取是在InitializeComponent
隐藏调用中创建标签之前发生的。如果你明确声明了无参数构造函数( Public Sub New()),那么VS IDE会将调用添加到InitializeComponent
,你可以在创建之后放置字符串变量的初始化。标签。
(如果在属性窗口中单击显示所有文件),您可以在Form1.Designer.vb
文件中找到InitializeComponent方法。
对于未来的知识,请考虑read this QA详细讨论NullReferenceException
的案例。