I have a Visual Studio project in which I have created a Visual Webpart. In the user control I have a panel which I want to display in edit mode and hide in browse mode.

ASP.NET code snippet:

<asp:panel runat="server" ID="myControl">

C# code snippet in user control code behind:

protected override void OnPreRender(EventArgs e)
    WebPartManager wpm = WebPartManager.GetCurrentWebPartManager(this.Page);
    if (wpm.DisplayMode == WebPartManager.BrowseDisplayMode)
        myControl.Attributes.Add("style", "display: none");
    else if (wpm.DisplayMode == WebPartManager.EditDisplayMode)
        myControl.Attributes.Add("style", "display: block");

This works, but if I have two webparts on same page and put on webpart is edit mode it shows the panel in both webparts.

How can I resolve this? Is there any better (or preferred) way to do it?

NOTE: I need to use display: none because the panel would be accessed via JavaScript.

Update 1:

I even tried writing code as this.myControl.Attributes.Add("style", "display: block"); but it still didn't work.

  • if you have two controls with the same Id it will find two of them and not know which one to use, makes sense right? I think this is your problem here – Gwny Aug 20 '15 at 11:52
  • @Gwny: Agreed. But the C# code runs in the user control's code behind. So all it should see is its on control. Right? If it is able to view something else then I think this is an issue. – Naveen Aug 20 '15 at 11:57

Each WebPart should have its own ID, and you can iterate over all WebParts in the manager (I don't do backend, but conceptually the same as front-end)

As for best pratice; don't mess with styles. Transfer all your display logic to CSS classes, and only set those Classes in your code. That way your presentation is a lot more loosly coupled with your backend code.

  • How would I identify current webpart by iterating over all the webparts? – Naveen Aug 20 '15 at 13:39

Your Answer

