Alex
Alex

Reputation: 3998

asp.net runat="server" c#name does not exist in the current context

I have the following asp.net div setup on my page:

<div runat="server" id="ImageContainer">
     <a href="<%# String.Format("/news/?Article={0}", Eval("ID")) %>"><img src="images/<%# Eval("Image") %>" class="ArticleImage"/></a>
</div>

and I know this is being created at the server as when I view it in developer tools its id is:

ctl00_body_ArticleInfoRepeater_ctl00_ImageContainer

which is being created by the server.

I now want to edit the Css under certain conditions by doing the following:

ImageContainer.CssClass = "invisibleClass";

My problem is, in the C# code I am getting the following error:

The name 'Image container' does not exist in its current context.

I have no idea why this is happening, as it clearly does exist.

Any ideas?

Upvotes: 0

Views: 935

Answers (3)

killer
killer

Reputation: 602

Controls placed on data list,repeater,grid-view are not accessed directly like other server controls placed on the page. If you want to access it through code behind you can access it on Data-bound or Item_command event of the repeater control because these controls itself act as containers for other controls placed on them.

you can use

   e.Items.findControl("controlID") to access a particular row controls.

I recommend you to study these two events of repeater control.

if you want to change class of all div with name imagecontainer , you can use javascript or jquery for doing it with few lines of code.

Upvotes: 1

Hiren Desai
Hiren Desai

Reputation: 1101

Are you using some databinding control such as GridView, Repeater or some other? The syntax <%#....%> represents data binding which works if it is placed inside some data binding control.

In such case you cannot access "ImageContainer" control directly. You have to search through parent control. Since you haven't mentioned what is parent control of "ImageContainer" it's hard to give code sample here... Though here is example how it can be done in GridView

Incase, if you haven't used DataBindingControl then I would recommand to check yourpage.aspx.designer.cs and you should be able to find control name there!

Hope this will be helpful.

Upvotes: 3

walther
walther

Reputation: 13598

That's because you're trying to reference a dynamically created object (obiviously inside a repeater). Firstly, you shouldn't set ID for dynamic objects created during runtime. IDs have to be unique, or else you'll run into problems.

Secondly, you need to get the parent object (probably the repeater itself or the container?) and then traverse the collection of child controls to find the one you're after. There are numerous answers about how to find a control in an asp.net webforms, so just google for a while and I'm sure you'll get the code.

For instance find control

Upvotes: 1

Related Questions