Aspx page doesn't compile when page is copied from another project - asp.net

I often have an issue with compile errors when I copy over an aspx page and code behind file from another project, it seems to work when I create another page and the content manually but if I just copy the files it won't. I have checked to make sure namespaces and references are ok but still doesn't make any sense. The error I get is:
Error The name 'txtUser' does not exist in the current context
I just wanted to understand why.
For e.g. I copied over the following:
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Login</title>
</head>
<body>
<form id="form1" runat="server">
<table align="center" width="300px" style="margin-top: 200px;">
<tr>
<td>
<legend>Login</legend>
<table style="width: 30%;" align="center">
<tr>
<td>
<asp:TextBox ID="txtUser" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</body>
</html>
ASPX.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtUser.Text = "text";
}
}

This is probably because the designer file is missing for the page. If it is, you can create it manually by right-clicking the page in the solution explorer and selecting 'Convert to Web Application'.

Are you copying the login.aspx.designer.cs. This file contains a partial class that holds the definition of the controls on the .aspx page.
e.g. for txtUser you'd have the declaration in the .designer.cs file.

One thing to check is if your new project has the same Project References as the old one.
If something is missing there (or indeed in your web.config references), VS can skip generating the designer.cs file altogether, resulting in the error you mention.

As far I look to u r posted questions and the code u copy :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Login" %>
You get this error because in u r designer page there is no textbox control
so it throws this error :
"Error The name 'txtUser' does not exist in the current context"
For more help can you paste the exact code u r coping.

Related

Web Form code behind not creating Partial Class, page inherits "ProjectName.ClassName" instead of just "ClassName". Visual Studio 2013

So I'm trying to make an "About" page that can be shared across many web applications that we use. To do this, I'm going to be saving the "AboutBox.aspx" and "AboutBox.aspx.vb" files on our web server. Then, from each application, I'll open a pop-up window that will call the AboutBox page by its url. The Problem I'm having is after I've created the page and copied it to the server, when I try to open the page it's giving me the error:
Parser Error Message: Could not load type 'DemoWebApp.AboutBox'.
Line 1: <%# Page Language="vb" AutoEventWireup="false" CodeBehind="AboutBox.aspx.vb" Inherits="DemoWebapp.AboutBox" %>
So I'm assuming it's having an issue with "Inherits" having the project name "DemoWebApp" in front of the class name.
Also, the code behind file that was created with the web form has "Public Class AboutBox" instead of what I think they're supposed to have which is "Partial Class AboutBox"
I've tried just getting rid of "DemoWebApp." from the inherits and also just changing the code behind to being a partial class instead of public. This didn't work.
Additionally, someone else created a test web form page from an older version of Visual Studio. This web form didn't have the project title in the inherits and had a partial class instead of public. This page was copied to the server and worked just fine.
I'm using Visual Studio 2013, I'm not sure if it's an issue with this version or something else entirely.
Is there any way that, when you add a new web form file to the project, it will create the file the way I need it to?
EDIT:
Here is my AboutBox.aspx code:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="AboutBox.aspx.vb" Inherits="TestAboutBox.AboutBox" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="height:238px; width:486px; background-color:green">
<form id="form1" runat="server">
<div style="width:154px; height:232px; float:left;">
<asp:Image ID="LogoImage" runat="server" Height="232px" ImageAlign="Middle" Width="154px" ImageUrl="small.png"/>
</div>
<div style="width:326px; height:232px; float:right">
<asp:Label ID="LabelProductName" runat="server" Text="Product Name" Font-Size="8.25pt" Font-Names="Microsoft Sans Serif" style="margin:5px"></asp:Label>
<br />
<asp:Label ID="LabelVersion" runat="server" Text="Version" Font-Size="8.25pt" Font-Names="Microsoft Sans Serif" style="margin:5px"></asp:Label>
<br />
<asp:Label ID="LabelCopyright" runat="server" Text="Copyright" Font-Size="8.25pt" Font-Names="Microsoft Sans Serif" style="margin:5px"></asp:Label>
<br />
<asp:Label ID="LabelCompanyName" runat="server" Text="Company Name" Font-Size="8.25pt" Font-Names="Microsoft Sans Serif" style="margin:5px"></asp:Label>
<br />
<asp:TextBox ID="TextBoxDescription" runat="server" Height="113px" Width="317px" Font-Size="8.25" Font-Names="Microsoft Sans Serif" TextMode="MultiLine" BackColor="#F0F0F0" style="margin:5px" ReadOnly="True">Description :</asp:TextBox>
<input type="submit" name="OKButton" value="OK" onclick="window.close();" id="OKButton" style="height:21px;width:75px;float:right; margin:5px" />
</div>
</form>
</body>
</html>
Aaand here's my AboutBox.aspx.vb file:
Public Class AboutBox
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
NOTE: I re-made the project under the name "TestAboutBox" since "DemoWebApp" was getting all messed up with me screwing around with stuff.
When you create a new Web Forms page from a Web Application project, it will create the page as described in the question. In order to get it the right way, the Web Form page needs to be made in a Web Site project. This page can then be used elsewhere.

VIsual Studio 2010 Design Mode Error Creating Control (Object reference not set)

Design mode has this problem site-wide since upgrading to .NET 4.0 / VS 2010 from 1.1 / 2003.
There's plenty to google on this and I've tried it all. What am I missing?
-Trying to debug from another instance of Visual Studio: Error Creating Control vs2010 MasterPage - there's not a whole lot of detail on how this is supposed to work. I started another empty instance of VS2010 and attached to devenv.exe. Set Debug->Break All. Switched to design mode in the website instance of VS. Ran the website instance of VS in debug mode. Nothing happens. I was hoping this could help because I DO have some user controls in the page. I can't find anything wrong with them though. Can I get more detail on how exactly to do this type of debugging? See the end of this post for the .aspx source.
-Commented out some <% =Session["Username"]%> junk in the tag of the page, since apparently accessing session stuff could cause this
-Checked the OnInit() method for dynamically adding controls or accessing uninstantiated objects. It's clean:
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cboURLFunction.SelectedIndexChanged += new System.EventHandler(this.cboURLFunction_SelectedIndexChanged_1);
this.cboStandard.SelectedIndexChanged += new System.EventHandler(this.cboStandard_SelectedIndexChanged);
this.cboType.SelectedIndexChanged += new System.EventHandler(this.cboType_SelectedIndexChanged);
this.chkLegacy.CheckedChanged += new System.EventHandler(this.chkLegacy_CheckedChanged);
this.btnRoute.Click += new System.EventHandler(this.btnRoute_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
.Aspx page source (thinned):
<%# Page language="c#" Codebehind="addRoute.aspx.cs" AutoEventWireup="false" Inherits="HTP.RHIO.WebPortal.addRoute" %>
<%# Register TagPrefix="HeaderControl" TagName="ucHeader" Src="ucHeader.ascx" %>
<%# Register TagPrefix="TopMenu" TagName="ucTopMenu" Src="ucTopMenu.ascx" %>
<%# Register TagPrefix="uc1" TagName="ucHelpLink" Src="ucHelpLink.ascx" %>
<HTML>
<HEAD>
<title>Add Route -
<% =Session["Domain"]%>
<% =Session["Username"]%>
</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
<link href="./style/WebPortalMain.css" type="text/css" rel="stylesheet">
<script type="text/javascript">
function jvsValidate() {
(removed for brevity)
}
</script>
</HEAD>
<body leftmargin="5" topmargin="0" rightmargin="5">
<form id="Form1" method="post" runat="server" onsubmit="return jvsValidate() ;">
<table id="Table1" class="tableWidth" cellspacing="0" cellpadding="0" border="0">
<!-- BEGIN HEADER ROW -->
<tr>
<td class="headerSection" colspan="3"><HeaderControl:ucHeader id="UcHeader1" runat="server"></HeaderControl:ucHeader></td>
</tr>
<!-- END HEADER ROW -->
<!-- BEGIN TOP NAV (IF NECCESSARY) -->
<tr>
<td class="topNavSection" colspan="3">
<table cellspacing="0" cellpadding="0" width="100%" border="0">
<tr>
<td style="WIDTH: 857px"><TopMenu:ucTopMenu id="UcTopMenu1" runat="server" xmlfilename="./MenuFiles/menu.xml" xslfilename="./MenuFiles/menu.xsl"></TopMenu:ucTopMenu></td>
<td align="right" width="15%"><uc1:ucHelpLink id="UcHelpLink1" runat="server"></uc1:ucHelpLink></td>
</tr>
</table>
</td>
</tr>
</table>
<br>
<table id="Table2" class="tableWidth" cellspacing="0" cellpadding="0" border="0">
<tr>
<td colspan="3"><img src="graphics/servicers_routes.gif"></td>
<td align="right">
<asp:hyperlink id="backLink" runat="server">
<img src="./graphics/back.gif" border="0"></asp:hyperlink></td>
</tr>
.
.
etc
.
</table>
<!-- END MAIN BODY SECTION --></form>
</body>
</HTML>
you will find your answer there : http://blogs.msdn.com/b/webdev/archive/2010/05/06/another-error-creating-control-in-the-design-view-with-object-reference-not-set-in-visual-studio-2010.aspx

UserControl with definable content (How to created templated user control)

A panel web control lets a developer put the panel on a page and define content that will appear inside the panel.
Is it possible to achieve similar functionality with a user control, where I define all my custom 'chrome' in the control, but am able to drop it on a page wherever I want and define the content inside on a per instance basis?
I think you are talking about a Templated User Control. Good luck!
Options:
1) Templated Controls as referred to by Uwe and Hanlet
2) jQuery UI library
3) ASP.NET 2.0 Web Parts
It's really tricky to implement no matter which way you go.
As Hanlet EscaƱo pointed out, this is complete possible to do. I'll show:
This is the user control markup:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TemplatedUserControl.ascx.cs" Inherits="Templated_User_Control.TemplatedUserControl" %>
<table border="1">
<tr>
<th>Head</th>
</tr>
<tr>
<td>
<asp:PlaceHolder ID="plContent" runat="server"></asp:PlaceHolder>
</td>
</tr>
<tr>
<td>Foot</td>
</tr>
</table>
This is the user control code:
using System;
using System.Web.UI;
namespace Templated_User_Control
{
public partial class TemplatedUserControl : System.Web.UI.UserControl
{
private ITemplate content_m = null;
[TemplateContainer(typeof(ContentContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate Content
{
get
{
return content_m;
}
set
{
content_m = value;
}
}
void Page_Init()
{
if (content_m != null)
{
ContentContainer container = new ContentContainer();
//This is the real magic. Take the contents, and put it in our ContentContainer object, then
//add the ContentContainer object as a child control of the placeholder so it renders inside the user control
content_m.InstantiateIn(container);
this.plContent.Controls.Add(container);
}
}
protected void Page_Load(object sender, EventArgs e) {}
public class ContentContainer : Control, INamingContainer {}
}
}
This is the page markup:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Templated_User_Control.Default" %>
<%# Register src="TemplatedUserControl.ascx" tagname="TemplatedUserControl" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:TemplatedUserControl ID="TemplatedUserControl1" runat="server">
<Content>
Template user control test.<br />
<asp:Literal ID="litTest" runat="server">this is a test!</asp:Literal><br />
abc 123!
</Content>
</uc1:TemplatedUserControl>
</div>
</form>
</body>
</html>
Yes, this is completely possible.
Here is a great example where a developer overrides an existing control (I chose an article with a Panel, since you used it as an example) and still allows content within.
The article is good, but you may find the sample code even more helpful.

Listview and SQLDataSource render nothing

I've never used either of these 2 controls before and I'm stuck with no visible rendering of the page (compiles and runs but produces nothing); I have no code behind file with this simple asp.net page and I am using Visual Studio 2008:
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="Index.aspx.cs" Inherits="zList.Index" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListView ID="CategoryList" runat="server"
DataSourceID="Categories">
<LayoutTemplate>
<ol>
<asp:PlaceHolder runat="server" ID="itemPlaceholder">
</asp:PlaceHolder>
</ol>
</LayoutTemplate>
<ItemTemplate>
<li><%# Eval("AttrDesc")%></li>
</ItemTemplate>
</asp:ListView>
</div>
</form>
</body>
</html>
<asp:sqldatasource runat="server" id="Categories"
ConnectionString="<%$ ConnectionStrings:ZIPeeeConnectionString2 %>"
SelectCommand="SELECT AttrID,AttrDesc FROM dbo.tblAttributes1">
</asp:sqldatasource>
Here is the connection string section from web.config (I have tried both connection strings separately and they both result in nothing rendered):
<connectionStrings>
<add name="ZIPeeeConnectionString" connectionString="Data Source=MOJITO;Initial Catalog=ZIPeee;Integrated Security=True" providerName="System.Data.SqlClient"/>
<add name="ZIPeeeConnectionString2" connectionString="Data Source=MOJITO;Initial Catalog=ZIPeee;User ID=sa;Password=" providerName="System.Data.SqlClient"/>
</connectionStrings>
I am getting no runtime errors and no errors during the build. The simple query works fine from SQL Query Analyzer (i.e. SQL Server 2000). Any ideas?
EDIT-UPDATE:
Here is what I have in my .ASPX.CS code behind file and I cannot get the debugger to stop on the breakpoint on the .DataBind method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace zList
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CategoryList.DataBind(); // breakpoint set here but debugger won't stop here
}
}
}
By the way, I fired up SQL Profiler and it appears the SQL select is not even being fired against
the server. As I said, the page is empty - just this junk when I scrape it via View Page Source:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title></title></head>
<body>
<form name="form1" method="post" action="Index.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMjAyMTkwMzQ3OQ9kFgQCAw9kFgICAQ8UKwACDxYEHgtfIURhdGFCb3VuZGceC18hSXRlbUNvdW50Av////8PZGRkAgUPD2QPEBYDZgIBAgIWAxYCHg5QYXJhbWV0ZXJWYWx1ZWQWAh8CZBYCHwJkFgMCAwIDAgNkZBgBBQxDYXRlZ29yeUxpc3QPZ2TCuhjvuwDRjaGJssTwiDXpAv/fdw==" />
</div>
<div>
</div>
</form>
</body>
</html>
I think the only thing wrong with this code is the placement of the sqldatasource. Can you place it inside the tag.
If that doesnt work, can you change your listview definition to
<asp:ListView ID="CategoryList" runat="server">
and then change your page load code to
CategoryList.DataSource = Categories;
CategoryList.DataBind();
You should be able to hit the debugger
As a last option, can you also check whether the connectionstrings is placed within the Configuration tag in web.config.

asp.net In a repeater is it possible to call a public function from another class?

Say I have this repeater which makes use of a public function called Test in the code-behind.
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("MyCol1")%></td>
<td><%# Eval("MyCol2")%></td>
<td><%# Test((int)Eval("MyCol1"))%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
In my code-behind, I have this function
public string Test (int Value)
{
return "Test"+Value.ToString();
}
This works fine but in my website I will have similar repeaters on various pages and most of them will need to call the Test function. Instead of having it in the code-behind of each web page would it be possible to put it in a public static class and call it directly from the repeater? Something like this (which does not work):
<td><%# MyStaticClass.Test((int)Eval("MyCol1"))%></td>
The only solution I've come up with would be to change the function in the code-behind to:
public string Test (int Value)
{
return MyStaticClass.Test(Value);
}
But it would be neater if I didn't have to put any code in the code-behind of each webpage (ie I would prefer the repeater to call the static function directly).
Any ideas or suggestions?
Create a Base class for your pages and put your common function there. So it will be available for all inherited child pages.
Can't
<td><%# Test((int)Eval("MyCol1"))%></td>
Be represented by
<td><%# Eval("MyCol1", "Test: {0}") %></td>
Or is there more to your test function that that?
I typically create a class for shared/static functions in my websites. This class can then be called from any page in the site and allows the code to be seperated from your UI or presentation code.
clsGlobal.cs
namespace testClass
{
public class clsGlobal
{
public static int EvalNumber(int value){
int localInt = 5;
return localInt + value;
}
}
}
Default.aspx
Option 1
This version imports the namespace of the global class into the aspx page so you can reference your static functions without using the namespace. "clsGlobal.EvelMethod()"
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="testClass._Default" %>
<%# Import Namespace="testClass" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Static Class Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%= clsGlobal.EvalNumber(5).ToString() %>
</div>
</form>
</body>
</html>
Default.aspx
Option 2
This version calls the static function using the fully qualified function name including the namespace. "testClass.clsGlobal.EvalNumber()"
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="testClass._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Static Class Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%= testClass.clsGlobal.EvalNumber(5).ToString() %>
</div>
</form>
</body>
</html>
Do you use a master page? You could drop it in there if you do.
I would do something like this:
On every content page that inherits from the master page you need:
<%# MasterType VirtualPath="[path to your master page]" %>
This allows you to get to the public methods on the master.
On your content page, whenever you need to call the Test method:
Master.Test([your int value]);
The accepted answer, and other answers here, suggest that inheritance is necessary to solve this problem. This confused me, so I asked my own question - How to call functions in a Class file, when inside a Repeater, without inheritance - and thanks to #Walsharoo I found out I merely needed to add the Project Name and I could call a static function (in a Class) from inside a repeater:
<td><%# [ProjectName].ClassName.MyStaticFunction(Eval("MyColumnName"))%></td>
This may prove helpful to others, I hope, though I'm not suggesting you're all as daft as me for forgetting this simple trick.

Resources