1,105,331 Community Members

changing the text of a button

Member Avatar
Oracle1986
Newbie Poster
10 posts since Mar 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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.

Member Avatar
hericles
Veteran Poster
1,078 posts since Nov 2007
Reputation Points: 98 [?]
Q&As Helped to Solve: 232 [?]
Skill Endorsements: 14 [?]
Featured
 
2
 

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";
}
Member Avatar
Oracle1986
Newbie Poster
10 posts since Mar 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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";
            }
        }
Member Avatar
tinstaafl
Postaholic
2,009 posts since Jun 2010
Reputation Points: 559 [?]
Q&As Helped to Solve: 400 [?]
Skill Endorsements: 35 [?]
 
1
 

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.

Member Avatar
Oracle1986
Newbie Poster
10 posts since Mar 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Question Answered as of 1 Year Ago by hericles and tinstaafl
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article