how to use codebeside in ASP.NET Web Application - asp.net

I'm using VS2008 and want to create a web application (not a web site) with Code-Beside
but, the default mode of aspx is Code-Behind.
I have tried to change the CodeBehind=ClassFile.cs to CodeFile=ClassFile.cs in the header of aspx's <%#Page%> part, and deleted the aspx.designer.cs file,but if I added a server control to the page, the compiler is also send me an error of no member defined.the cs file is the orinal file of codebehind, it is partial class.

You don't want to delete aspx.designer.cs you want to delete the aspx.cs file, then place a similar file next to it and declare it as a partial class. designer.aspx.cs is still required to provide you direct access to controls placed within the page, rather than going through FindControl.

You definitely don't want to delete the .designer.cs file, as this is where the server control definitions will be placed.
In general the codebehind model is much better as it makes the code easier to find, use and maintain.

Related

The name does not exist in the current context

I have a masterpage in my asp.net 3.5 application and I have some controls and jquery stuff. I try to access the controls in codebehind and it says :
The name 'DrpStates' does not exist in the current context
Why it is not accessible in codebehind ?
When you create a code behind file, ASP.NET also automatically generates a designer file (which is right next to it). In that designer file all the controls are initialized and loaded. Sometimes (for reasons unknown) when you create a new control, it fails to re-initialize the designer file and you can't get access to the control in the code behind file.
Try doing this >
Delete the designer file (right click > delete)
Right click on the aspx file > Convert to Web Application
Should work now
It's probably part of the master page or parent page, try using FindControl method:
this.Page.FindControl("DrpStates");
There could be a problem with your .designer.cs file. Check if you have a designer file with the same name as your aspx (or ascx) file.
If you open the aspx file and switch between design view and html view and back it will prompt VS to check the controls and add any that are missing to the designer file.
Try right clicking on the aspx and select "Convert to Web Application".
You can also try deleting the .designer.cs file and then recreate an empty file with the same name.
reason : - When we create a code behind file, ASP.NET also automatically generates a designer file. In that designer file all the controls are initialized and loaded. Sometimes when we create a new control, it fails to re-initialize the designer file and you can't get access to the control in the code behind file.
There is a simple Solution to this situation.
Step1 : open the the yourfile.aspx.designer.cs file
you will find things like " protected global::System.Web.UI.WebControls.Label Label2; "
these are the initialized components in the sequence in which they were generated by you.
Step2: just copy and paste the following line repeatedly for every missing component that were not
recognized by the code behind : "global::System.Web.UI.WebControls."+Class of the component that you are missing + single space + id of the missing component.
Step3: save the file and voila all the components error disappear magically.

Compile web application project ascx into dll

Is it possible to compile a web application project .ascx (user control) into a dll?
I want to do the following:
Use the same control in multiple websites
Embed css and .js as resources into the control
Be able to update super easy. If the user control updates, I just want to update 1 .dll
I have successfully followed this article, http://msdn.microsoft.com/en-us/library/aa479318.aspx.
However, that uses web site projects, and I cannot embed js css as resources into web site projects.
Any ideas? Am I going about this wrong, should I change the approach?
Conversion is easy, and could even be fully automated. It simply requires changing a few settings and base classes in the DLL Project you want your ASCX controls embedded in.
1... For each UserControl, set the ASCX file's Build Action (under Properties) to "Embedded Resource", and delete its associated designer file.
2... Save the project.
3... Right click the project and choose "Unload Project".
4... Right click it again and choose the "Edit *.csproj" option.
Change sections that look like this (where the asterisk represents your class name):
<Compile Include="*.ascx.cs">
<DependentUpon>*.ascx</DependentUpon>
<SubType>ASPXCodeBehind</SubType>
</Compile>
to look like this
<Compile Include="*.ascx.cs" />
That will cause the code-behind files to be compiled independently of the ASCX files.
5... Save changes, and right click the project and choose "Reload Project".
6... Open all your "*.ascx.cs" files and make them inherit from the following custom UserControl class, instead of the System.Web.UI.UserControl class (you may need to locate parent classes to complete this step).
public class UserControl : System.Web.UI.UserControl
{
protected override void FrameworkInitialize()
{
base.FrameworkInitialize();
string content = String.Empty;
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream( GetType().FullName + ".ascx" );
using (StreamReader reader = new StreamReader(stream))
content = reader.ReadToEnd();
Control userControl = Page.ParseControl( content );
this.Controls.Add( userControl );
}
}
This base class will take care of loading and parsing the embedded ASCX file.
7... Finally, you may need to place ASCX files in subfolders so that their resource names (automatically determined by folder path) match the full type name of their associated class (plus ".ascx"). Assuming your root namespace matches your project name, then a class named "ProjectName.Namespace1.Namespace2.ClassName" will need its ASCX file in a subfolder "Namespace1\Namespace2", so it gets embedded with the name "ProjectName.Namespace1.Namespace2.ClassName.ascx".
And that's it! Once you compile the DLL and include it in another project, you can instantiate instances of your user controls using the "new" operator, like any other class. As always, your control will be "caught up" to the current page event once added as a child control to the page or another control on the page.
It is difcult to use user controls in this way due to the markup ascx file. If you want to create reusable control libraries your are much better off creating custom controls.
Another way would be to convert user control to the custom control. There is an nice article on MSDN: Turning an .ascx User Control into a Redistributable Custom Control which describes exactly how to do that. Here is the summary:
Write your user control as you normally would, typically using the Visual Studio designer.
Test it using a simple page before trying to deploy it.
Deploy the application to precompile it.
Grab the user control's assembly produced by the deployment step,
and you're essentially done: You have your custom control.
Finally, use your custom control in other apps the same way as you
always use custom controls.
Hope this helps.
I had to do it once and I followed this article
http://www.codeproject.com/KB/user-controls/EmbeddedUserControl.aspx
It's based on the possibility of mounting a virtual file system on different places (an assembly, database, etc)
There are quite a few articles out there on how to do exactly that:
http://www.nathanblevins.com/Articles/Compile-a-Web-User-Control-into-a-DLL-.Net-c-.aspx
http://blogs.msdn.com/davidebb/archive/2005/10/30/487160.aspx
I know this is old, but yes its possible.. I do it all the time, see https://kocubinski.wordpress.com/2013/05/06/compile-asp-net-webforms-ascx-usercontrols-into-assembly-for-re-use/

codebehind cannot reference the page controls

I have controls in ascx file but i can't see them in intellisense in .cs file.It was working nice before.
I can see the control names in designer.cs file.
I have deleted the Asp.net temp files in AppData folder but still not working.The other user control files in the app can reference coerrectly to it's page controls. What is the problem here ?
I use VS2008.
Look at the top line of the .ascx page and check out the value of Inherits= and make sure that is has the right namespace.class appropriate for your codebehind. For example if your namespace is ProjectNamespace and your control class is MyControl then it should be ProjectNamespace.MyControl. This can get out of synch if you renamed the ascx file, etc and cause this type of problem.
This happens to me every time I copy a user control from one project to another. The connection between the ascx and the code-behind breaks.
This solution is tedious but it gets around the problem:
Create a new User Control. Visual Studio will correctly connect the ascx file to ascx.vb file.
Copy the ascx and vb code from your original control into the new one.
Delete your original control.
You now have a working control, but it has a different name.
If it is important to retain the name of the original control, repeat the whole process again and copy the second control to a third one with the correct name.
Write to Microsoft and ask them to stop adding bells and whistles we don't need and fix the basic stuff!
I just figured this out for my situation: in the Page parameters of the .aspx file, the 'Codefile' parameter was pointing to the file name: 'LabEdit.aspx.cs'. It should have been pointing to the path: "~/WOPages/LabEdit.aspx.cs". I know I didn't move the codefile or the page file, so this is maybe a problem with VS2008
I have solved the problem, I have uninstalled and reinstalled VS2008 and it is solved.

Getting namespace name not found for ASP.net user control

So I'm having problems when I try to publish the website.
I'm in visual studio 2008 sp1.
I've got a bunch of user controls and on a few pages I'm using them programatically.
I've got a reference on the aspx page
<%# Reference Control="~/UserControls/Foo.ascx" %>
Then on the code behing I use
ASP.usercontrols_foo newFoo control = (ASP.usercontrols_foo)Page.LoadControl("~/UserControls/Foo.ascx");
If I navigate to the page it works fine, but when I goto publish the website I get a compile time error.
Argh, I'm bleeding development hours on this same issue. Does anyone have a solution to this ?
BTW: It builds if you uncheck "Allow this precompiled site to be updatable" (Right-click on the website, choose Property Pages, MSBuild Option)
But I need the site to be updatable.
I had this same problem - actually, in my case I could get it to compile and build my website, but it would blow up spectacularly when doing an automated build.
Try replacing your code as follows:
ASP.usercontrols_foo newFoo control = (ASP.usercontrols_foo)Page.LoadControl("~/UserControls/Foo.ascx");
with
USERCONTROLS_Foo newFoo control = (USERCONTROLS_Foo)Page.LoadControl("~/UserControls/Foo.ascx");
(Capitalization will be based on how you capitalized your directory name/control name - but in either case should highlight appropriately).
Specify a namespace for user control (see Dynamically Load a user control (ascx) in a asp.net website ).
I've found a solution for it. If i'll declare controls in user defined namespace, then I can use controls directly without using ASP or referencing it into aspx page.
It may have something to do with the specific type not being available. Can you change the control reference so the type and cast just use the base Control class:
Control control = Page.LoadControl("~/UserControls/Foo.ascx");
Yes, I can cast it to Control. But then I lose direct access to the methods on the usercontrol.
I know that I can access the methods by reflecting into the control, and I've successfully done that but that's far from ideal to access all the other user controls on the site.
Also, the follow-up error is that it cant find the usercontrols that on the markup
<%# Register src="CategoryRows.ascx" tagname="CategoryRows" tagprefix="abc" %>
<abc:CategoryRows ID="CategoryRows" runat="server" />
Note that I can run the site successfully both locally and on the server if I essentially XCopy the entire site (source code and all). But Publish fails.
Casting the user control may create many problem .my approach is to create a class (say control Class) put all the properties and method you need after casting and inherit this class from System.Web.UI.UserControl .Then in your user cotrol code file instead of System.Web.UI.UserControl user this control class .
now when ever you need casting cast with this class only . it will be light casting as well.
Please check:
Do you have any website.publishproj file?
If it exists, then delete and try again and publish code.

Linking an ASP.NET web page to another project's code file

I have a series of .NET 2.0 web pojects that have identicle code behind in their web pages. The only thing that is different is how the html is laid out.
Is there a way that I can have a main web project that holds all the code behind (including control events like button click) and so that the other web projects reference the web page code file to this project's code files?
Edit: Note that the changes in html include exclution of certain controls, I am catoring for this by using the FindControl method so that if the control doesnt exists, I would simply have a null value.
You may try putting all the code-behind classes into a library and inheriting from a common base-class.
You can take a look at "Skin File" file type of Visual Studio. On the other hand you can learn if it works for you from the address below: http://msdn.microsoft.com/en-us/library/ykzx33wh(VS.80).aspx

Resources