Daniel Halachev Daniel Halachev - 21 days ago 7
C# Question

How to make text of a button change according to a condition(C#)

I am working on a project in VS C#, but I need some help. I have a Horizontal Split Container, Panel 1 of which contains a Menu Strip, and Panel 2 contains 2 more panels, Panel 1 of which acts like a Sidebar. I have added a button in the Menu Strip, which aims to hide or show the sidebar, depending on the condition

splitContainer2.Panel1Collapsed == false
.

However, I want the text of the button to change accordingly - eg. from "Hide Sidebar" to "Show Sidebar". How should I do this?
Here is all the code:

private void hideSidePanelToolStripMenuItem_Click(object sender, EventArgs e)
{
if (splitContainer2.Panel1Collapsed == false)
{
splitContainer2.Panel1Collapsed = true;
}
else splitContainer2.Panel1Collapsed = false;
}


And here is a Screenshot:
Something like this. I am unable to show the list of the View button, because of the program I am using, but I hope you get the point.

Answer

You need to change the .Text property of the Button / ToolStripItem:

private void hideSidePanelToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (splitContainer2.Panel1Collapsed == false) 
    {
        splitContainer2.Panel1Collapsed = true;
        hideSidePanelToolStripMenuItem.Text = "Show Sidebar"
    }
    else {
        splitContainer2.Panel1Collapsed = false;
        hideSidePanelToolStripMenuItem.Text = "Hide Sidebar"
}
Comments