I have this code in my Site.master :
<%# Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="SiteMaster" %>
<!-- ... -->
<AnonymousTemplate>
[ <asp:HyperLink ID="LoginHyperLink" runat="server" EnableViewState="false">Log In</asp:HyperLink> |
<asp:HyperLink ID="RegisterHyperLink" runat="server" EnableViewState="false">Register</asp:HyperLink> ]
</AnonymousTemplate>
I have this code in my Site.master.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
// ...
protected void Page_Load(object sender, EventArgs e)
{
// this is just placeholder for now.
RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
}
I'm getting a Compile-Time error in Visual Studio 2010 at the RegisterHyperLink.NavigateUrl saying :
"The name 'RegisterHyperLink' does not exist in the current context."
Not really sure what's up. I've seen this work in non-Master pages, so does this just not work in Masters?
I'd think it would...
It´s a bug, add a new HyperLink in Desing/Source save and try again. Delete the new hyperlink to finish
Ensure that your code-behind is inheriting from System.Web.UI.MasterPage.
Ensure the aspx has the appropriate directive added and that it is spelt right with correct case:
<%# Master Language="C#" CodeFile="Site.master.cs" Inherits="MasterPage" %>
It is because of this AnonymousTemplate. It probably creates new naming container thus is not directly accessible from Page_Load.
Related
I have following project structure where web application may contain user controls from the same web project or from a separate class library. The issue is in Default.aspx.cs, when I execute usercontrol2.SetValues(); I receive NullReferenceException since for some reason textbox2 is null. I've tried using EnsureChildControls(); but it does not help either. Should I register or invoke these usercontrols in some other way? Why does not it work out-of-box?
User control in web project
WebUserControl1.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" %>
<asp:TextBox runat="server" ID="textbox1"></asp:TextBox>
WebUserControl1.ascx.cs
namespace WebApplication1
{
public partial class WebUserControl1 : System.Web.UI.UserControl
{
public void SetValues()
{
textbox1.Text = "Hello";
}
}
}
User control in class library
WebUserControl2.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl2.ascx.cs" Inherits="ClassLibrary1.WebUserControl2" %>
<asp:TextBox runat="server" ID="textbox2"></asp:TextBox>
WebUserControl2.ascx.cs
namespace ClassLibrary1
{
public partial class WebUserControl2 : System.Web.UI.UserControl
{
public void SetValues()
{
textbox2.Text = "world";
}
}
}
Main page
Default.aspx
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<%# Register tagPrefix="web" tagName="WebUserControl1" src="WebUserControl1.ascx" %>
<%# Register TagPrefix="web" Namespace="ClassLibrary1" Assembly="ClassLibrary1" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<web:WebUserControl1 runat="server" ID="usercontrol1"></web:WebUserControl1>
<web:WebUserControl2 runat="server" ID="usercontrol2"></web:WebUserControl2>
</asp:Content>
Default.aspx.cs
using System;
using System.Web.UI;
namespace WebApplication1
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
usercontrol1.SetValues(); // OK
usercontrol2.SetValues(); // NullReferenceException
}
}
}
Using ascx usercontrols from a different assembly is not possible.
I think you should look at this problem this way. Your classlibrary is compiled into a dll-file. This is the only thing that is available for your webapplication. The ‘ascx’ doesn’t get compiled into the dll, and is not available.
If you really want to keep some controls separated from your web-project, I think there are a few options:
Convert your usercontrol to a customcontrol. Custom controls are a bit more difficult to create, but it is certainly not impossible. This way you really get a re-usable control.
See also this question; it addresses your problem and there’s also a link to an algorithm which ‘converts’ an ascx usercontrol to a custom control. (I didn’t test that)
Asp.NET user control referenced from another project/dll has NULL properties
Make sure your ascx files are available to the web-project, by publishing to a path in your output. Then use LoadControl to load them serverside. This could work, but I also think some of the reusability from your classlibrary is lost.
I have an aspx file that will contain a lot of sections and I would prefer to have each section in its own include file. I'm okay to put all of the code behind into the main file. I'm using: <!-- #include file ="section1.aspx" --> in the body. When I build (I'm still only including the first section with code), I get "The name 'lbl_phone' does not exist in the current context" because the code behind has a routine that references this screen field which IS in the include file. What is a better way to go about this?
Edit (as it is now, hope I cut it down properly here, builds good now but error in browser):
file ola.aspx
<%# Page Language="C#" AutoEventWireup="true" Inherits="_ola" Codebehind="ola.aspx.cs" %>
<%# Register TagPrefix="section" TagName="account" Src="account.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><body><form id="ola_form1" runat="server">
<section:account id="section_account" runat="server" />
</form></body></html>
file: ola.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
public partial class _ola : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lbl_phone.Text = "000-000-1234";
}
}
file: account.ascx
<%# Control Language="C#" ClassName="_ola" CodeBehind="account.ascx.cs" %>
Call us at <asp:Label ID="lbl_phone" runat="server" Text="lbl_phone"></asp:Label>
At runtime in the browser, I get: Object reference not set to an instance of an object. (for the line with lbl_phone.Text = ...)
Don't use server side includes. They don't work well in the ASP.NET architecture.
Instead, embed reusable stuff into .ASCX user controls. MSDN How To article.
ASCX File MyControl.ascx
<% # Control Language="C#" ClassName="Spinner" %>
<table>
<tr><th>Column 1</th><th>Column 2</th></tr>
<tr><td>Some content</td><td>Some more content</td></tr>
</table>
Then this can be embedded on as many ASPX pages as you like.
<%# Register TagPrefix="uc" TagName="MyControlName" Src="~\Controls\MyControl.ascx" %>
<uc:MyControlName ID="MyControl1" runat="server" />
Edit- You should make these ASCX files as portable as possible in your application so that they're self contained units. There shouldn't be much of a need for your ASPX code behind to reference a control contained in the ASCX file. You can do code behinds for user controls (MyControl.ascx.cs or MyControl.ascx.vb) if necessary, or you can use a script block to embed the code directly in the ASCX page.
.NET Framework will not follow server side includes and so it won't compile properly if you try to reference a control that is being included via SSI. But you could potentially reference a control in an ASCX file. For example...
MyAdvancedControl.ascx
<% # Control Language="C#" ClassName="Spinner" %>
<asp:Label runat="server" id="lbl_phone" />
<script runat="server">
public Label Lbl_phone {get {return lbl_phone;}}
</script>
MyPage.aspx
<%# Register TagPrefix="uc" TagName="MyAdvancedControlName" Src="~\Controls\MyAdvancedControl.ascx" %>
<uc:MyAdvancedControlName ID="MyControl2" runat="server" />
MyPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
MyControl2.Lbl_phone.Text="Galaxy S4";
}
Controls defined as part of a Page or Master Page or User Control are private by default. To get around that, add a public property that exposes it. Put this property in account.ascx.cs
public Label lbl_phone_public_version{
get {
return lbl_phone;
}
}
When you try to reference lbl_phone from code on ola.aspxcs, you have to do it through the parent control, like this:
protected void Page_Load(object sender, EventArgs e)
{
section_account.lbl_phone_public_version.Text = "000-000-1234";
}
Using Microsoft Visual Web Developer 2008 here with a ASP.NET Web Application created by default.
I create a label control with ID="Label1" control in designer view within the Default.aspx file, than I go to Default.aspx.cs file and type in Label1.Visible = False; I immediately get Label1 underlined in red, and hovering over this code says that the Control does not exist in the Current Context.
So, how am I supposed to manipulate properties of a control?
Ok, so in the Default.aspx file, there is this:
<asp:Label ID="Label1" runat="server"></asp:Label>
In that same file very first line says this:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
In Default.aspx.cs, I have this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace IDSS
{
public partial class _Default : System.Web.UI.Page
{
Label1.Visible = False;
}
}
Label1.Visible is not defined in the current context? When I start typing the word Label, I see only "Label" in there, Label1 is not in there at all. If I selected Label and place a dot after it, I get only 2 options: Equals and ReferenceEquals
In Default.aspx.designer.cs there is this:
public partial class _Default {
protected global::System.Web.UI.WebControls.Label Label1;
}
What is the problem here?
Define something like:
<asp:Label ID="Label1" runat="server" />
in you .aspx page. It should automatically create the realated definition in the .designer file. You do not need to manually create the definition in the designer file. If you do, then make sure it is a partial class...for your page.
i am trying to get that AjaxFileUpload-Control(used in ContentPage) working. But it does not fire OnUploadComplete Event at server side
I am using version 4.1.60919.0 of the ControlToolkit. I have tried everything i found on the internet.
Here just a few steps:
Added enctype="multipart/form-data" method="post" to the form-element in my MasterPage
Nested the AjaxFileUpload into an UpdatePanel with UpdateMode=Always
Tried events UploadedComplete and OnUploadComplete, but stayed at the second one
Added a try-catch-block in the EventHandler to catch unknown exceptions and print the ExceptionMessage to a label on the site --> nothing happened
Tried it with(out) a ThrobberImage...
Many other tipps that did not work...
So, i hope we will find a solution together in this community. Heres my markup:
<%# Page Title="New Download" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="NewDownload.aspx.cs" Inherits="Internals_NewDownload" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<ajax:ToolkitScriptManager ID="ToolkitscriptManager" runat="server"> </ajax:ToolkitScriptManager>
<h1>Create a new Download</h1>
<ajax:AjaxFileUpload ID="FileUpload" runat="server" ThrobberID="ThrobberLabel" OnUploadComplete="FileUpload_UploadComplete" />
<asp:Label ID="ThrobberLabel" runat="server" Style="display: none;"><img alt="UploadingPicture" title="Please wait while uploading..." src='<%= Constants.DomainString + "/Data/Images/loading-small.gif" %>' /></asp:Label>
<asp:Label ID="DownloadLabel" runat="server"></asp:Label>
</asp:Content>
And this is my CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Internals_NewDownload : System.Web.UI.Page
{
private string m_LanguageCode;
protected void Page_Load(object sender, EventArgs e)
{
if (RouteData.Values.ContainsKey("LanguageCode"))
m_LanguageCode = RouteData.Values["LanguageCode"].ToString();
//if (IsPostBack)
// return;
if (!User.IsInRole("Administrator") && !User.IsInRole("Kunde") && !User.IsInRole("Mitarbeiter"))
Response.Redirect(Constants.DomainString + "/PermissionDenied.aspx");
Session[Constants.NonGlobalizedString] = true;
Session[Constants.MenuInfoSession] = new ClsMenuInfo("NewDownload");
}
protected void FileUpload_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
try
{
string filePath = "~/upload/" + e.FileName;
DownloadLabel.Text = filePath;
}
catch (Exception ex)
{
DownloadLabel.Text = ex.Message;
}
}
}
Please, if you have ANY idea, do not hesitate to let me know it. I am very confused as i think that i just did in that howtos i found on the internet...
Thanks in advance!
Take into account that AjaxFileUpload control use contextkey QueryString parameter to detect own postback. I believe the reason of you issue is that this parameter lost in result of rewriting url.
I'm not expert in applying routing but in my opinion you need to register contextkey parameter in routing tables and tweak AjaxControlToolkit sources to use RouteData instead of Request.QueryString for retrieving it value.
Check this link for more info: AjaxControlToolkit Source Code
hello everyone i am writing a program which captures a part of the screen when a button is clicked. Below is my code
**default.aspx**
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="_9marchexp._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
To learn more about ASP.NET visit www.asp.net.
</p>
<p>
You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
</p>
<p>
</p>
<p>
</p>
<p>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</p>
</asp:Content>
and
default.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.IO;
using System.Data;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace _9marchexp
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Rectangle formRect = this.Bounds; // saving information aout your window in formRect <br/>
// (height, width, x, y, etc
using (Bitmap bitm = new Bitmap(formRect.Width, formRect.Height)) // creating new bitmap of the same <br/>
// height and width as our own window
{
using (Graphics graphic = Graphics.FromImage(bitm))
{
graphic.CopyFromScreen(new Point(formRect.Left, formRect.Top), Point.Empty, formRect.Size);
}
bitm.Save("C:\\Users\\xxxx\\Desktop\\myscreenshot.jpg", ImageFormat.Jpeg); // saving the bitmap bile to destination dir. <br/>
// with specified name
}
}
}
}
however the thing is when i execute the code an error message is displayed
***'_9marchexp._Default' does not contain a definition for 'Bounds' and no extension method 'Bounds' accepting a first argument of type '_9marchexp._Default' could be found (are you missing a using directive or an assembly reference?)***
How to correct that, can someone help me??
also if i replace this.Bounds with Screen.PrimaryScreen.Bounds the code runs perfectly but the screenshot of the whole screen is taken which i don't want.
It is impossible to capture the screen of the browser, or of the user, or of the server, or of the desktop or what ever, using the code behind.
A solution that read a page and print it to an image can be found here
Convert webpage to image from ASP.NET