2

How to access a server-side div in code behind (inside content page)?
mean there is a div in content page like below:

<div id="MyDiv" runat="server">
</div>

but the code below does not work:

 MyDiv.Style.Add("display", "none"); 

EDIT
I am so sorry and that was my mistake!
The codes upper are correct and work perfect and there is no problem about them. My mistake was about my css and after fixing it every thing was ok.
so really thanks for attention and answers.

peterh
  • 11,875
  • 18
  • 85
  • 108
SilverLight
  • 19,668
  • 65
  • 192
  • 300

5 Answers5

5

to access element from content page you can use below code:

HtmlGenericControl myDiv = (HtmlGenericControl)MyDiv;
myDiv.Style.Add("Display", "none");
Amir
  • 714
  • 1
  • 13
  • 37
  • 1
    I have this on my .aspx page: `
    `. When I access it from code-behind: `content.Visible = false;` I receive the following error: `The name 'content' does not exist in the current context`
    – Si8 Jul 21 '14 at 15:43
0

try that code:

MyDiv.Style["display"] = "none";

some other variants here:How do you change the style of a div programatically

Community
  • 1
  • 1
Frank59
  • 3,141
  • 4
  • 31
  • 53
  • dear bro, thanks for the answer. but there is no problem about my syntax. that MyDiv is like -> ContentPlaceHolder1_MyDiv in content page and this is the problem. besides there is no problem in content page about -> MyDiv.... and this is why i am confused! – SilverLight Nov 25 '12 at 16:50
  • You can use RegisterStartupScript(http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx) with javascript for change style for ContentPlaceHolder1_MyDiv. But i think is not good way – Frank59 Nov 25 '12 at 16:58
0

What about:

MyDiv.Visible = false;

Note that this causes the div not to render at all on the page, so you can't access it on the client side to make it visible later.

Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
0

note that if you set an id to your tag which includes non-allowed characters like (-) you will not be able to access it in code-behind.

<div id="myDiv" runat=server"> content goes here... </div>

in code-behind:

myDiv.visible=false;

that will work.

Ali.Rashidi
  • 1,284
  • 4
  • 22
  • 51
0

For those using Amir answer getting the 'The name '(element id)' does not exist in the current context' try opening the designer.cs file of your asp page and manually add your html element: protected global::System.Web.UI.HtmlControls.HtmlGenericControl elementidhere;

bryan
  • 3
  • 1
  • 3