Hey all,

How can I change the text of a button each time a user clicks on it?

For example, I have a button "Connect", if connection is successfull I want to change the text to "Disconnect" and vice versa. For now I dont have any function that checks if the connection is successfull so for the meantime I just want the button text to be updated every time a user clicks on it.

If you only have the two options that the text can be a simple if statement inside the button click function is the easiest option.
Check if the current text is "Connect" and if so change the text property to "Disconnect" and vice versa.

if(connect.text == "Connect") {
    connect.text = "Disconnect";
} else {
    connect.text = "Connect";
}
commented: but check if the connection is successful not the button text. +1

Thanks, but now the text of the button doesn't change on the first click.

   private void btnConnect_Click(object sender, EventArgs e)
        {
            if (btnConnect.Text == "Connect")
            {
                 btnConnect.Text = "Disconnect";
            }
            else
            {
                 btnConnect.Text = "Connect";
            }
        }

What text is in the button to start with? If it's not Connect exactly then it won't work right. For instance if you included the & when you set the text in the design window you have to include it in the code as well.

Thank you very much, I had "&" in the text property and forgot to remove it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.