开发者

Hiding a servercontrol

开发者 https://www.devze.com 2023-02-02 08:34 出处:网络
How can i hide a control thats located on my aspx file from within the aspx.cs file? I have a textbox and a button, and the idea is when i press the button both those controls disapear and a dynamic

How can i hide a control thats located on my aspx file from within the aspx.cs file?

I have a textbox and a button, and the idea is when i press the button both those controls disapear and a dynamic control appears. Basicly a way to make it invisible would to place something in the click event of that button o开发者_如何学Pythonr is there a other way?

Or would there be a better way to sovle this without having to make the control actually "unvisible"?

Thanks.


In the event handler of your button's click event, set the desired controls Visible property to false. You could also accomplish this via jquery without a postback, i.e. OnClientClick.


EDIT

Ok, the css approach below will mean that your control still renders but will be made invisible by the browser but will still be there in the mark up. If you don't want to it render at all set the visible to false as other guys here have mentioned.

It's one of those where there are many ways to skin this particular cat and it really depends what you want to achieve :)

Original Post

You can change it's cssClass to one that contains display:none;

<style type="text/css">
.ShowMyControl
{
  display:block;
}

.HideMyControl
{
  display:none;
}
</style>

Then in your code behind you can flip the styles on the button_click...

MyControl.cssClass = "ShowMyControl";

Or

MyControl.cssClass = "HideMyControl";

What you may want to do though is place your controls in asp:Panel controls and then flip the cssClass of the Panel instead of on each control. That'll work too.

This is one way to do it based on the server side model you appear to be using, however, you may want to look at utilising AJAX calls & JavaScript to do the dynamic showing & hiding on the client side. This may not be appropriate though - it depends on your design pattern really


You can subscribe to a server-side Click event of the button and set the Visible property of your user control to false:

protected void cmdHide_Click(object sender, EventArgs e)
{
    myCustomControl.Visible = false;
}

However this will cause in your custom control not to be rendered at all. Furthermore the page will be reloaded since you're using server-side event.

If you don't want the page to be reloaded then you can hide it using Javascript:

Markup:

<asp:Button ID="cmdHide" Text="Hide" runat="server" />
<asp:Panel ID="myPanel" runat="server">
    <cust:MyCustomControl ... />
</asp:Panel>

Code-behind:

cmdHide.OnClientClick = string.Format("document.getElementById('{0}').style.display = 'none'; return false;", myPanel.ClientID);

-- Pavel

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号