单击vb.net后更改按钮的文本

时间:2013-11-15 07:27:37

标签: vb.net

这有点简单,而且非常愚蠢。但我看不出我错过了什么......

    Private Sub btnmode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnmode.Click
    If Me.btnmode.Text = "COMMAND MODE" Then
        Me.btnmode.Text = "DATA MODE"
        sPort.Write("$$$")
    End If
    If Me.btnmode.Text = "DATA MODE" Then
        Me.btnmode.Text = "COMMAND MODE"
        sPort.Write("$$$" & vbCr)
        sPort.Write("exit" & vbCr)
    End If

End Sub

enter image description here

使用此代码,我应该可以在单击后更改其文本。但为什么不呢?什么都没发生。

2 个答案:

答案 0 :(得分:1)

在这种情况下使用select case,它会更具可读性。

select case ucase(Me.btnmode.Text)

case "COMMAND MODE"
    Me.btnmode.Text = "DATA MODE"
    sPort.Write("$$$")
case "DATA MODE"
    Me.btnmode.Text = "COMMAND MODE"
    sPort.Write("$$$" & vbCr)
    sPort.Write("exit" & vbCr)

End Select
代码中找到

问题

    If Me.btnmode.Text = "COMMAND MODE" Then
        Me.btnmode.Text = "DATA MODE" '--------> Text been set as DATA MODE
        sPort.Write("$$$")            '    |
    End If                            '    |
                                      '    |
   If Me.btnmode.Text = "DATA MODE" Then ' ---------> Here again                                       
       Me.btnmode.Text = "COMMAND MODE"  '    you are checking the Text with 
       sPort.Write("$$$" & vbCr)         '    DATA MODE and you are assigning
       sPort.Write("exit" & vbCr)        '    the text back to COMMAND MODE
   End If  

所以我猜我的按钮文本最初设置为“命令模式”。因此,您的按钮文本拒绝还原。

答案 1 :(得分:0)

If Me.btnLoad.Text = "COMMAND MODE" Then
    Me.btnLoad.Text = "DATA MODE"
    sPort.Write("$$$")
ElseIf Me.btnLoad.Text = "DATA MODE" Then
    Me.btnLoad.Text = "COMMAND MODE"
    sPort.Write("$$$" & vbCr)
    sPort.Write("exit" & vbCr)
End If