When you set the 'GroupingText' property of the asp:panel control then It will render as the 'fieldset' tag in HTML and whatever set in the 'GroupingText' property value is rendered as the <legend>
tag.
I think following code will help you as per your requirement.
For Design side,
<asp:Panel runat="server" ID="Panel1" GroupingText="This is legend">
<h4>Your Content Goes Here</h4>
</asp:Panel>
<br />
<asp:Button ID="btnHidePanel" runat="server" Text ="Hide FieldSet" onclick="btnHidePanel_Click" />
<asp:Button ID="btnShowPanel" runat="server" Text ="Show FieldSet" onclick="btnShowPanel_Click" Visible="false" />
For Code-behind try this,
protected void btnHidePanel_Click(object sender, EventArgs e)
{
Panel1.Visible = false;
btnHidePanel.Visible = false;
btnShowPanel.Visible = true;
}
protected void btnShowPanel_Click(object sender, EventArgs e)
{
Panel1.Visible = true;
Panel1.GroupingText = "This Legend Text Has been Changed";
btnHidePanel.Visible = true;
btnShowPanel.Visible = false;
}