How to change public properties of User control? - asp.net

I have a very simple user control in my web site project which has public property declarations as following
public DateTime StartDate
{
get
{
return _startDate;
}
set
{
_startDate = value;
}
}
public DateTime EndDate
{
get
{
return _endDate;
}
set
{
_endDate = value;
}
}
When i drag the ascx file to one of my aspx page and when i go to code behind of aspx page i can access the controls properties through intelisense, but when i run the project through visual studio i get error "The name 'uctTest1' does not exist in the current context " any suggetions to fix the error?
This is the line where Error shows when i run the project uctTest.StartDate = DateTime.Now;
aspx page markup :
<%# Page Language="C#" AutoEventWireup="true" CodeFile="removetest.aspx.cs" Inherits="removetest" %>
<%# Register src="~/uctTest.ascx" tagname="testCtl" 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:testCtl ID="uctTest1" runat="server" />
</div>
</form>
</body>
</html>
aspx page code behind :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
uctTest1.StartDate = DateTime.Now;
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
}

It seems that you are missing the #Register directive in the .aspx file referring to path of .ascx control.
http://msdn.microsoft.com/en-us/library/c76dd5k1(v=vs.71).aspx

I had another aspx page with different file name in the website project that another developer had copied from my aspx page which had same <%# Page Language="C#" AutoEventWireup="true" CodeFile="aspxpagename.aspx.cs" Inherits="aspxpageClass" %> directive in that copied page. Even though that copied paged didnt have user control strangely page I was working reported the error. Changing that page directive's codefile,inherits attributes to different values fixed the issue.

Related

Accessing Properties of the code-behind from aspx page in web application project

I have a property x in my code-behind file in a web application project. It gives me compile time error while it does not give any error in website project
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="test.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%= x2 %>
<%# x2 %>
</div>
</form>
</body>
</html>
Codebehind file :
using System;
namespace test
{public partial class WebForm1 : System.Web.UI.Page
{
public int x2 = 2;
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
It is working fine when I use the same technique in my website project
Kindly help
Thanks
Check if there are any other errors in your code behind WebForm1.aspx.cs.
like missing reference or any other compile error.
This works for me. Are you sure there's a value in ViewState? On form load add a value to test.
ViewState["FormMode"] = "ViewApplicant";
lblMessage.DataBind();
Also make sure the label has some text to view. It could be showing but is empty.
<asp:Label ID="lblMessage" runat="server"
Text="some text"
Visible='<%# FormMode == "View" || FormMode == "ViewApplicant" %>'>
</asp:Label>
Your code is perfectly okay. While accessing the variable/property initillay, the red underline may appear under the expression indicating the compile error, but when you build the solution, there should be no error.
Your original post has changed so here's a new answer.
Try removing the namespace from the code behind and change 'inherits' on the page to Inherits="WebForm1".
page directive:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="WebForm1" %>
code behind:
using System;
public partial class WebForm1 : System.Web.UI.Page
{
public int x2 = 2;
protected void Page_Load(object sender, EventArgs e)
{
}
}
'Inherits' must match the partial class name.

How to create multiple code behind file for .aspx page

I have a situation where I need to create multiple code behind files for a single .aspx page in c# asp.net. Actually I have a web form on that huge coding is done and I need multiple developer's working on it simultaneously. How can I achieve the same?
Here is the code snippet I tried
Class 1 MyPartialClass.cs
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void PrintText(string pt)
{
Response.Write(pt);
//lblTest.Text = pt; //Can not access this label in partial class.
}
}
}
Class 2 which is Default.aspx.cs
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PrintText("Hello World");
}
}
}
and my HTML source
<%# Page Language="C#" AutoEventWireup="false" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblTest" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
ASP.NET will always generate your code behind files as partial classes
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
You can therefor separate the code behind in different files, if you pertain the definition as partial and keep the class under the same namespace.
Edit : The Web Project
//Default.aspx
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label>
</asp:Content>
//Default.aspx.cs
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PrintText("Hello World");
}
}
}
//MyPartialClass.cs
namespace WebApplication1
{
public partial class Default
{
protected void PrintText(string pt)
{
Response.Write(pt);
lblTest.Text = pt; //lblTest is accessible here
}
}
}
I haven't modified any other generated files. One thing I like to mention is that the Default.aspx.cs file that has been generated was generated with the class name "_Default". I have changed it to Default and Visual Studio refactored the change across all files that contain a definition for that class, except the Default.aspx file, where I had to manually modifiy from Inherits="WebApplication1._Default" to Inherits="WebApplication1.Default".
Edit 2:
I kept searching the internet, and according to http://codeverge.com/asp.net.web-forms/partial-classes-for-code-behind/371053, what you are trying to do is impossible. Same idea is detailed at http://codeverge.com/asp.net.web-forms/using-partial-classes-to-have-multiple-code/377575
If possible, consider converting from Web Site to Web Application, which supports what you are trying to achieve. Here is a walkthrough on how to perform this conversion: http://msdn.microsoft.com/en-us/library/vstudio/aa983476(v=vs.100).aspx
You need to set up a source safe server in order to that, like Team Foundation Server.
You can easily just add partial classes to your code.
http://www.codeproject.com/Articles/709273/Partial-Classes-in-Csharp-With-Real-Example

Dynamically creating ASP.NET Web User Control contain AJAX Extender is throwing error "Extender controls may not be registered after PreRender"

I am trying to dynamically add a web user control that contains an AJAX collapsible panel with a Gridview inside the panel when a user clicks on a button. I am able to add a single instance of the user control but when I add additional user controls it throws the following error:
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Extender controls
may not be registered after PreRender.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
I am new to ASP.NET Development and the method I am using to handle postbacks is to store the user controls in a list and add them again on prerender method call. I am not sure what to do or if I am handling the creation of the user controls correctly. Any advice is appreciated.
Here is the back end code:
public partial class Test : System.Web.UI.Page
{
private IList<Control> _persistedControls;
private const string PersistedControlsSessionKey = "thispage_persistedcontrols";
static int count = 1;
private IList<Control> PersistedControls()
{
if (_persistedControls == null)
{
if (Session[PersistedControlsSessionKey] == null)
Session[PersistedControlsSessionKey] = new List<Control>();
_persistedControls = Session[PersistedControlsSessionKey] as IList<Control>;
}
return _persistedControls;
}
protected void Page_Load(object sender, EventArgs e)
{
PersistedControls();
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
IList<Control> controlsToGenerate = PersistedControls();
// regenerate dynamically created controls
foreach (var control in controlsToGenerate)
{
MasterPanel.Controls.Add(control);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Control control = LoadControl("~/WebUserControl/UseCaseSetupUserControl.ascx");
control.ID = "uc" + count++.ToString();
MasterPanel.Controls.Add(control);
_persistedControls.Add(control);
MasterPanel.Controls.Add(new LiteralControl("<br />"));
_persistedControls.Add(new LiteralControl("<br />"));
}
}
Here is the ASPX Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
<!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">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<br />
<asp:Panel ID="MasterPanel" runat="server">
</asp:Panel>
</div>
</form>
</body>
</html>
Create your controls as early as possible in the Page life cycle.
Since you have the PersistedControls on load, that is where you should add them to the controls collection. The best place to add controls in Init.
If you really can't do that then use Load.
If this must be done on an event, then you can add the control there for the first time, but persist it and remember to add it back on Init or Load from the next postback onwards.
If you add controls after PreRender they cannot add any of their data to the ViewState. SaveViewState occurs just before PreRender. A lot of controls rely heavily on the ViewState to function properly. The exception is simply telling you that you should add your control earlier on in the Page lifecycle.

How to dynamically render a control?

How do I go about rendering an asp.net control on a web page from a string in code behind?
For example, say I have the aspx page below:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="nrm.FRGPproposal.Questionnaire1" %>
<!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>
//want to render a text box here
</div>
</form>
</body>
</html>
What could I do in my Page_Load event to render a TextBox into the div?
protected void Page_Load(object sender, EventArgs e)
{
//what do i do here to render a TextBox in the div from the aspx page?
}
Caution there may be compilation problems here. But basically add a placeholder control to the code in front as such.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="nrm.FRGPproposal.Questionnaire1" %>
<!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:placeholder id="placeHolder" runat="server"/>
</div>
</form>
</body>
</html>
Then create a TextBox in the code behind programmatically. You will need to include System.Web.UI in order to get the textbox.
Then Add the control to the controls collection on the placeHolder. Set whatever properties you like on the text box programmatically
protected void Page_Load(object sender, EventArgs e)
{
TextBox tb = new TextBox();
placeHolder.Controls.Add(tb); //tb is referring to the name that you want to name your element. in this example given was TextBox. so the name of text box is tb.
}
Easy.
Add two attributes to your div element : <div runat="server" id="myDiv"></div>
Then
TextBox tb = new TextBox();
this.myDiv.Controls.Add(tb);
If you want to render a Custom UserControl you can use the above code
MyUserControl control = (MyUserControl)Page.LoadControl("~/My_VirtualPathToControl");
this.myDiv.Controls.Add(control);
(You must register your control in the aspx file)
One more think.
Be cautious when you execute code on Page_Load event.
You will also need to rebuild the controls in the Page_Init method in order to read the controls' state/values on PostBack.
protected void Page_Init(object sender, System.EventArgs e)
{
TextBox tb = new TextBox();
placeHolder.Controls.Add();
}

ASP.NET 4.0 Database Created Pages

I want to create ASP.NET 4.0 dynamic pages loaded from my MS SQL server. Basically, it's a list of locations with information. For example:
Location1 would have the page www.site.com/location/location1.aspx
Location44 would have the page www.site.com/location/location44.aspx
I don't even know where to start with this, URL rewriting maybe?
Url rewriting addresses a different problem than what you are describing.
You can use an HttpHandler that handles requests to the path location and parse the last segment to get your lookup key then simply pass execution off to an .aspx. Although you are passing execution off to a general page, the url will remain as entered.
I will provide an example. Give it a shot. here is a sample project
LocationHandler.cs
using System.IO;
using System.Web;
namespace DBHandler
{
public class LocationHandler : IHttpHandler
{
#region IHttpHandler Members
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
string page = Path.GetFileNameWithoutExtension(request.Url.Segments[request.Url.Segments.Length - 1]);
// for url ~/location/location33.aspx page will be 'location33'
// do something interesting with page, perhaps
context.Server.Execute("~/locations.aspx?locationId=" + context.Server.UrlEncode(page));
}
public bool IsReusable
{
get { return false; }
}
#endregion
}
}
locations.aspx
<%# Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Request["locationId"];
}
</script>
<!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:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
web.config excerpt
...
<system.web>
...
<httpHandlers>
<add verb="*" path="location/*.*" type="DBHandler.LocationHandler"/>
</httpHandlers>
</system.web>
...

Resources