Asp.net code behind not able to access controls in ascx - asp.net

I am fairly new to the .NET scene and have run into a small problem with a simple asp.net app and accessing controls defined on in a .ascx file in the code behind.
Here is my Default.ascx file:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<p>
<asp:Label AssociatedControlID = "userText" AccessKey = "L" runat="server" ID="userLabel">Username</asp:Label>
<asp:TextBox ID = "userText" runat="server" MaxLength="20" ></asp:TextBox>
</p>
</asp:Content>
Here is the Default.aspx.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_PreInit(object sender, EventArgs e)
{
userLabel.Text = "Hello!";
}
}
As you can see, pretty straight forward, all I am trying to do is change the text property of a label programmatically. However when I run this I am getting a NullReferenceException, userLabel is not set to an instance of an object. Shouldn't userLabel be a property of my _Default class? I tried explicitly setting userLabel as a property but I get an compile time error saying that userLabel already has a definition.
I imagine I am missing something very simple here but I'm not sure what it is. Could anyone tell me what I am doing wrong? Thanks much!

Page_PreInit is called before controls are rendered. Try adding your code to the Page_Load method.
See Life-Cycle Events section in http://msdn.microsoft.com/en-us/library/ms178472.aspx

Controls are not available until they are initialized; the control has not yet been created at the PreInit event which is why you cannot access it.
Setting values like you are doing should generally be performed at the Load event, or at least after the page Init event has fired.

As you can read here, in the page_perinit you cannot access control because they does not yes exist.
Is a good practice apply theme and personalization during this event, not access the state of the controls

Initialization of controls should be done on Page_Init.
protected void Page_Init(object sender, EventArgs e)
{
userLabel.Text = "Hello!";
}

First of all, you can't simply access label in user control with userLabel.Text. You need to get with Label lbl = (Label)UserControlID.FindControl("userLabel"); in your parent page. (But what you need is to set vale of Label in UserControl from Parent page.)
So I would do as:
Put property in UserControl:
public string UserName {get; set;}
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = this.UserName;
}
In page load event of Parent Page, set property value:
protected void Page_Load(object sender, EventArgs e)
{
UserControlID.UserName = "Hello!";
}
Page_Load of parent page will call before usercontrol's page load and it should be ok.

I don't see any label named userLabel. The name of your label seem to bel userText.

Related

ASP.NET passing variables from web form to code behind

i'm developing a web application for my company, but i'm coming up against a very simple problem that i don't now how to resolve. I search a lot on internet but i can't find anything.
I need to call a code behind method from an asp.net controls passing variables.
This is the method in the code behind (file.aspx.cs):
protected void SayHello(object sender, EventArgs e, String RandomName)
{
Response.Write(PrintedString);
}
And this is a asp.net control that call the method through OnLoad event :
<asp:Label ID="Label1" runat="server" Text="Hello" OnLoad="Visibility('ciao mamma')"></asp:Label>
What's wrong with this simple thing? Where i'm wrong?
Please answer to this simple question, it's driving me crazy...Thanks.
You can pass an argument to the event handler by the following way, but please note it will work for only asp button.
<asp:Button ID="btn" runat="server" Text="Click" OnCommand="btn_Command" CommandArgument="YourArgumentValue"/>
and then in the code behind file you do like this :
protected void btn_Command(object sender, CommandEventArgs e)
{
Response.Write(e.CommandArgument);
}
It will work for only asp button because they have a onCommand attribute with them.
whenever you will click on the button this code behind file code gets executed.
Hope this helps.
You can set the value to label on Page_Load event
You can use below code.
protected void Page_Load(object sender, EventArgs e)
{
string UserName="test";
Label1.Text="Hello "+ UserName;
}
Is this what you need?
Markup:
<asp:Label ID="lbl" runat="server"><%=SayHello("foo") %></asp:Label>
Code behind:
protected string SayHello(string name)
{
return "Hello " + name;
}

AjaxFileUpload doesn't fire OnUploadComplete Event

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

how to call function from html file in asp.net

i'm new to asp.net
i want to call function from my html file
I have a html file containing a list of menu
Menu 1
and i have a file name home.aspx, i want to call a function in home.aspx.cs with that hyperlink
I have tried this but still can not
Call a C# function in ASP.NET when clicking on a HTML link
sorry for my English, English is not my native language
please help me
is my first code name home.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="home.aspx.cs" Inherits="user_home" %>
<% Response.WriteFile("tools/menu.htm"); %>
and this is home.aspx.cs
public partial class user_home : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e){
}
and this is my menu.htm
<div id="menu">
<ul>
<li>Menu1</li>
</ul>
</div>
sorry for trouble
Menu 1
You should use runat="server" attribute.
Are you sure you are not looking for a LinkButton???
This control renders in the client as:
Click me...
ASPX
<asp:LinkButton Text="Click me..." runat="server" ID="myLink" Click="myLink_Click" />
Code behind
protected void myLink_click(object sender, EventArgs e)
{
// write here your cool stuff as a response of the click event
}
If you insist to use an HtmlControl, then:
In ASPX
Menu 1
IN code behind
protected void myLink2_Click(object sender, EventArgs e)
{
// write here your cool stuff as a response of the click event
}

ASP.NET Web Forms multiple views and the lifecycle of controls that are not Visible

Given a scenario where a page/control should display different views (like tabs) in different circumstances (query string argument, postback from a control, user setting retrieved from the database) I would normally put a control like MultiView or Placeholder and switch the active view index or the Visible property like this:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="TestWebApplication.WebForm2" %>
<%# Register Src="SomeControl.ascx" TagName="SomeControl" 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>
<asp:PlaceHolder runat="server" ID="phControl" Visible="false">
<uc1:SomeControl ID="SomeControl1" runat="server" />
</asp:PlaceHolder>
<asp:PlaceHolder runat="server" ID="phNotControl" Visible="false">
Some other content
</asp:PlaceHolder>
</div>
</form>
</body>
</html>
And I would switch the views in a code behind depending on the logic like this:
using System;
namespace TestWebApplication
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
phControl.Visible = false;
phNotControl.Visible = true;
}
}
}
This is the control:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="SomeControl.ascx.cs" Inherits="TestWebApplication.SomeControl" EnableViewState="false" %>
I am the control
And the code behind of the control:
using System;
namespace TestWebApplication
{
public partial class SomeControl : System.Web.UI.UserControl
{
protected void Page_Init(object sender, EventArgs e)
{
Response.Write("I am the control's Init and I am executing heavy operations <br />");
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("I am the control's Load <br />");
}
protected void Page_PreRender(object sender, EventArgs e)
{
Response.Write("I am the control's PreRender and I am only called if the control is Visible <br />");
}
}
}
However what if the control in question has some relatively heavy work to do (calling the database) in its init and load events? They get executed even if the control is not Visible and will slow down the page. One possible solution I see is moving all the work in the PreRender method of the child control because it is not executed for controls which are not visible. However this will not work if the control accepts user input from some dynamically populated control (think of dropdownlist) because the logic that populates the dropdown with options will not be executed.
I've come up with the following solutions:
Move the heavy work in the PreRender method and wrap it in an if(!IsPostBack). Then let the ViewState hold the possible values for the dropdown and ASP.NET will restore it. The downside is that it is using ViewState and bumping up the size of the page.
Create the control dynamically with LoadControl and add it in the placeholder from code behind. This will trigger catch up events and the code that populates the dropdown can be put in the Init method where it belongs. The downside is that the layout is defined in the code behind. Looking at the markup one cannot see what controls are on the page and looking at the code behind it is not clear where the control will appear. It also makes styling and other "design" operations more difficult.
Leave it like it is. The downside is that there will be additional database queries and if there are a lot of views these would add up.
My actual question is how I solve this problem without putting stuff in the ViewState, without multiple queries and without dragging my layout into the code behind.
Could it be a solution to make an AJAX call for your heavy database work?
Then you could display the View and in the background load the data you need and display it. The page would load really fast and you could display some indication that data is currently being loaded.
How about creating a public method on in your user controls, such as InitControl(). Do all the heavy work within InitControl() instead on page load. Then, on parent page, when page is being shown, call InitControl.
using System;
namespace TestWebApplication
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
phControl.Visible = false;
phNotControl.Visible = true;
SomeControl1.InitControl();
}
}
}
Don't do any work within OnLoad event of your user controls.

ASP.NET page with base class with dynamic master page not firing events

I am feeling that I have terribly wrong somewhere. I was working on a small asp.net app. I have some dynamic themes in the \theme folder and have implemented a page base class to load the master page on the fly. The master is having the ContentPlaceHolder like:
<asp:ContentPlaceHolder ID="cphBody" runat="server" />
Now I am adding pages that are derived from my base class and added the form elements. I know, Visual Studio has problem showing the page in the design mode. I have a dropdown box and wish to add the event of onselectedindexchange. But it is not working. the page is like this:
<%# Page Language="C#" AutoEventWireup="true" Inherits="trigon.web.Pages.MIS.JobStatus" Title="Job Status" AspCompat="true" CodeBehind="JobStatus.aspx.cs" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphBody" runat="Server">
<div id="divError" runat="server" />
<asp:DropDownList runat="server" id="jobType" onselectedindexchange="On_jobTypeSelection_Change"></asp:DropDownList>
</asp:Content>
I have also tried adding the event on the code behind like:
protected void Page_Load(object sender, EventArgs e)
{
jobType.SelectedIndexChanged += new System.EventHandler(this.On_jobTypeSelection_Change);
if (!IsPostBack)
{
JobStatus_DA da = new JobStatus_DA();
jobType.DataSource = da.getJobTypes();
jobType.DataBind();
}
}
protected void On_jobTypeSelection_Change(Object sender, EventArgs e)
{
//do something here
}
Can anybody help?
Regards,
set AutoPostBack="true" on your dropdown

Resources