我在几年内没有使用visual basic编程,但我有这个代码,可以将温度从华氏温度转换为celcius。问题是当您在其中一个文本框中输入数字时,会得到重复的数字且值不正确。我认为它与Handles有关但我在这里很丢失,有什么想法吗?
Public Class MainForm
Private Sub FahrenheitTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FahrenheitTextBox.TextChanged
CelciusTextBox.Text = 5 / 9 * (Val(FahrenheitTextBox.Text) - 32)
End Sub
Private Sub CelciusTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CelciusTextBox.TextChanged
FahrenheitTextBox.Text = (9 / 5 * (Val(CelciusTextBox.Text)) + 32)
End Sub
End Class
答案 0 :(得分:1)
这本身并不是一个答案,但我想提出一些在评论中不会出现的建议。如果您正在使用TextChanged事件,则应该防止不需要的事件,例如,键入一个文本框,该文本框会触发TextChanged,这会导致另一个文本框发生更改,触发TextChanged,导致您键入的文本框发生更改
尝试这样的事情:
Public Class MainForm
Private textChanging As Boolean = False
Private Sub FahrenheitTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FahrenheitTextBox.TextChanged
If Not textChanging Then
textChanging = True
CelciusTextBox.Text = 5 / 9 * (Val(FahrenheitTextBox.Text) - 32)
textChanging = False
End If
End Sub
Private Sub CelciusTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CelciusTextBox.TextChanged
If Not textChanging Then
textChanging = True
FahrenheitTextBox.Text = (9 / 5 * (Val(CelciusTextBox.Text)) + 32)
textChanging = False
End If
End Sub
End Class
此外,您应该使用CStr
将数字转换为字符串,就像使用Val
将字符串转换为数字一样:
Private Sub FahrenheitTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FahrenheitTextBox.TextChanged
If Not textChanging Then
textChanging = True
CelciusTextBox.Text = CStr(5 / 9 * (Val(FahrenheitTextBox.Text) - 32))
textChanging = False
End If
End Sub
最后,我重新标记了你的问题 - 这是VB.NET,而不是VB6。谢谢!