“The Controls collection cannot be modified because the control contains code blocks” - asp.net

While trying to insert controls in my page with the following block of code, i got this exception
The Controls collection cannot be modified because the control
contains code blocks
Literal lite=new Literal();
lite.Text = #"<div class='cookieLaw_slidesharey'><a id='cookieLaw_slideshare' href='#'><img src='/img/content/cookielaw_slideshare.jpg'/></a></div>";
Control control = this.FindControl("PlaceHolder");
control.Controls.AddAt(0,lite);
I tried to follow the advices written in this thread:
"The Controls collection cannot be modified because the control contains code blocks"
Which are basically:
replacing <%= %> with <%# %>
And adding
Page.Header.Databind() in the page load
But i get the following exception:
Object reference not set to an instance of an object.
Thank you for your help.
PS: i'm using .NET 3.5

Check if your "PlaceHolder" has a runat=server attribute. That should already help. You can address that control by it's id then instead of using FindControl.
The reason why your Page.Header.Databind() is not working is probably because you don't have a head section with the runat=server like in the example you copied from. They were adding controls in the header there which can be slightly different.

Related

displaying session value instead of code itself in aspx

<%= Session.Item("user_fullname")%>
this supposed to display session value right?
but mine is displaying code itself....
Note: I have included aspx page in another aspx, like:
<% Response.WriteFile("../etc/header1.aspx") %>
the displaing session code is inside header1.aspx
anyone knows how to display session value?
Session items would be stored as an Object. You need to cast to the correct type:
<%= (string)Session.Item("user_fullname") %>
When using Response.WriteFile("../etc/header1.aspx"), the usual Page Life cycle will NOT be executed for the mentioned header1.aspx page.
Since there will be no asp.net page life cycle processing , the inline code
<% %> won't be executed at all and therefore all such statements will be displayed as it is.
Response.WriteFile() is used to write just the Contents of a file, which can contain HTML , Controls, directly to the output stream.

Server tags not working inside asp controls

Alrighty to make this quick:
I want to set start and end dates for a calendar extender dynamically on-change or on page load
the values are put into hidden fields on the .ascx and populated during page load in an if not postback
one set of calendar extenders is in the item template field of a grid view call this set A
the others are in a normal html table - set b
set a and set b have flags StartDate="<%# hfStart.value%>" EndDate="<%# hfEnd.value%>"
set a in the item template of a grid view column works like a charm
set b in the HTML table doesn't appear to work at all
What gives?
So far I have tried other server tags with the same code inside but I am obviously missing the salient detail. Why does one work and not the other?
UPDATE: Tried
CDate(hfstart.value).ToString with <%: and <%= tags
<%= hfstart.value %>
Unless I misunderstand, <%= will fire at the very END of the asp.net life cycle stopping it from being useful in this context.
As it turns out you DO need to use <%# %> within asp tags as others like <% %> and <%= %> execute at the end of the ASP.NET life cycle and get spit out the buffer to god knows where. When using <%# %> however, the asp control needs to be DataBound(); at the appropriate time.
This happens automatically for controls modeled in the <item template> tags in the gridview because everything within the gridview is bound on its gridview.DataBound() command.
Could it be because you're using the <%# %> tags which are for data binding? This would explain why they work in the GridView, because it supports data binding.
However in a basic HTML table you should use <% %> tags instead, or <%= %> to call a method.
For full details of the tag types, try this reference.

How to pass an object from .cs to .aspx

I am a asp .net beginner. I want to use some objects created at Site.Master.cs in Site.Master. Is there an easy way to do it?
I know how to do it in MVC(by using view(the object)). But how can i do it in normal ASP .net web application?
I don't understand what exactly you want to do.
If you want to insert some string into tag's title you can insert the following thing in SiteMaster.master file:
<img src="<%= Page.ResolveUrl("~/") %>images/logo.png">
instead of:
<img src="images/logo.png">
In the first case there will be calculated the path from the root of your application. In the second case there will be relative link. This is because server will CALCULATE the value of Page.ResolveUrl("~") function and will WRITE it in src tag.
You can do the same thing with any other methods, classes if you defined them properly. But I wouldn't recommend you to implement complicated logic in .aspx files (or .master files). Because you can end up with many difficulties with testing and styling such application.
There are other server tags:
<% %> - an embedded code block is server code that executes during the page's render phase. The code in the block can execute programming statements and call functions in the current page class. Description and examples
<%= %> - most useful for displaying single pieces of information. Description and examples
<%# %> - data binding expression syntax. Description and examples
<%$ %> - ASP.NET Expression. Description and examples
<%# %> - Directive Syntax. Description and examples
<%-- --%> - Server-Side Comments. Description and examples
<%: %> like <%= %> - But HtmlEncodes the output (new with Asp.Net 4). Description and examples
Another way: you can use JSON to send some data to the client and then process it with javascript. Take a look at this project.
If the #Page directive in your .aspx file has Inherits="XYZ" where XYZ is the class declared in your .cs file, you can simply add a protected field to your class and assign a value to it. You'll be able to access it in the .aspx file just by using its name.
You can also use HttpContext.Items property to keep objects during a single request:
HttpContext.Current.Items["SavedItem"] = "hello world";
And use it in page:
<%= ((string)Context.Items["SavedItem"]) %>
Any public or protected property or method in Site.Master.cs will be accessible from Site.Master.
but how to invoke c# code in aspx ?
There are several ways, including the <%= %> construction, and databinding syntax.
It would help if you explained what you're trying to achieve.

Create a usercontrol instance programmatically in ASP.NET

I have a UserControl that I need to add dynamically. I tried to follow this MSDN article, but I'm not having any success....
http://msdn.microsoft.com/en-us/library/c0az2h86.aspx
The UserControl is basically an image gallery, and it loads some pictures based on an ID. My idea was to make this ID available as a property. Then when I create an instance of the control, I could set this ID and add it to the form.
I added a reference to the control in the .aspx page that will use it, like this:
<%# Reference Control="~/PictureGallery.ascx" %>
And in the UserControl I added a ClassName like this:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="PictureGallery.ascx.cs"
Inherits="PictureGallery" ClassName="PictureGallery" %>
When I try to create an instance in the .aspx.cs like the article suggests, Dim gallery As ASP.PictureGallery, I get an "Type ASP.PictureGallery is not defined".
The article mentions a namespace, ASP, and I tried importing it to the .aspx.cs with no luck.
So, I'm not able to get a reference to the UserControl.
How can it be fixed?
It sounds like you are confusing two separate ways of working with a UserControl.
One way is to register the control on your page so that you can put it into the page at Design Time e.g.
<div>
<asp:PictureGallery id="myGallery" runat="server" MyProperty="SomeValue">
</asp:PictureGallery>
</div>
The second is programmatically (or dynamically) adding it into the page at runtime in your code behind. If so, then you need to use the LoadControl function which is mentioned in the sample. You do not need to register the control in the aspx file if you do this.
e.g.
Dim gallery as PictureGallery = LoadControl("~/PathToControl/gallery.ascx")
gallery.MyProperty = "SomeValue"
placeHolder.controls.add(gallery)
edit
What is the class name of the control in the code behind...something like this:
Partial Public Class MyControlsClassName
Inherits System.Web.UI.UserControl
That is the type you need to use when you declare it. Is it within a namespace perhaps?
I don't think you've placed the control in your code behind. You may well have created the reference, but do you have a tag such as <asp:PictureGalary id="gallary"></asp:PictureGalary> anywhere in your aspx?
The ASP namespace is generated at run time- user controls get "compiled" as they are used by .aspx pages so this is why you get the error message "Type ASP.PictureGallery is not defined".
When adding user controls dynamically you should use the Page.LoadControl method:
Page.LoadControl("~/PictureGallery.ascx")

Nested ASP.Net controls not defined

I have a couple of controls that are set to runat="server", but are showing up as "not declared" in the vb code behind. They are not being setup in the designer.vb file at all, even if the design.vb is re-created.
The only thing that I can think might be causing this is that the controls are inside of a custom control. The code looks something like this (it has been modified because of NDA):
<abc:MyCustomControl>
<additionalItems>
<asp:CheckBox id="coolCheckboxOfPower" runat="server" Text="Triple Rainbow!">
</asp:CheckBox>
</additionalItems>
</abc:MyCustomControl>
So using the example above, if I try to use coolCheckboxOfPower in my vb page, it says it is not declared.
It has been suggested to me that asp controls cannot be nested. Is this true, and if so, how do I get around that?
Asp controls can certainly be nested. Just look at asp:Panel, asp:ListView etc. You have to do some extra work when creating your control to enable this to happen. Namely you have to make have an ITemplate property on your control. Check out the following Building Templated Custom ASP.NET Server Controls to get you started

Resources