2

我已经好几年没有在 Visual Basic 中编程了,但是我有这个代码可以将温度从华氏温度转换为摄氏温度。问题是当您在其中一个文本框中输入数字时,您会得到重复的数字并且值不正确。我认为这与手柄有关,但我在这里很迷茫,有什么想法吗?

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
4

1 回答 1

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。谢谢!

于 2013-01-17T05:04:25.267 回答