Page_Load of 2. user control never executes (website) - c#

I am in the process of making a website that displays information in boxes.
There will be different pages with different combinations of boxes. They will have a lot of boxes in common.
Therefor, I am making the boxes as user controls to then put on the different pages. The different pages will also share a master page.
However, when starting development of the 2. box, I ran into a problem:
The Page_Load (or the whole code behind) of the 1. box runs fine, but the Page_Load og the 2. box gets ignored. This results in a lot of null values that makes the aspx file crash.
My CT1.aspx contains this to use the two user controls:
<%# Page Title="CustType1" Language="C#" MasterPageFile="~/MTCustomer/Master.master" AutoEventWireup="true" CodeFile="CT1.aspx.cs" Inherits="MTCustomer.CT1" %>
// Some HTML
<td ID="column1" style="width: 400px;">
<Box:CustomerInfoBoxAx runat="server" />
<Box:CustomerInfoBoxMt runat="server" />
</td>
// Some HTML
My Web.config contains this for the user controls to be usable:
<pages>
<controls>
<add tagPrefix="Box" tagName="InfoBoxA" src="~/Controls/InfoBoxA.ascx" />
<add tagPrefix="Box" tagName="InfoBoxB" src="~/Controls/InfoBoxB.ascx" />
</controls>
</pages>
My user control A looks lige this:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="InfoBoxA.ascx.cs" Inherits="Controls.InfoBoxA" %>
<% if (IsVisible("InfoBoxA") && Customer != null)
{ %>
<div>
<%-- Markup --%>
</div>
<% } %>
And box B looks like this:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="InfoBoxB.ascx.cs" Inherits="Controls.InfoBoxB" %>
<link rel="stylesheet" type="text/css" href="<%=VirtualPathUtility.ToAbsolute("~/Styles/InfoBoxStyle.css")%>">
<% if (IsVisible("InfoBoxB") && Customer != null)
{ %>
<div>
<%-- Markup --%>
</div>
<% } %>
I have tried to swap the order of the two user controls in the page.aspx, this also changed witch one had its Page_Load (or the whole code behind) ignored. Based on that, it looks like only the first code behind is executed, and the rest is ignored.
EDIT:
After following the exceptions that comes after the initial null reference exception, I can see that the Page.DataBind() in the first user control is still executing. This must mean that this is what causes the aspx file of both box one and two run. But how do I get around this?

Problem solved.
I removed Page.DataBind() from all user controls, and in the CT1.aspx.cs (the page code behind) i moved it from Page_Load() to OnLoadComplete().
By doing this, Page_Load() in all files have been executed before the Page.DataBind() is executed.

Related

Can not disable ViewState

I have made a simple Web Form where I try to get rid of the ViewState. When I run it and press Go the label gets the value of whatever I put in the texbox. So far all good. But the textbox maintains the value I filled in. As far as I understand it this is done by the ViewState mechanism. What do I miss?
<%# Page Language="C#" AutoEventWireup="true" Inherits="SportsPlay.Sida1" ViewStateMode="Disabled" EnableViewState="false" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server" enableviewstate="false">
<div>
<asp:TextBox runat="server" ID="txtTest" ></asp:TextBox>
<asp:Button runat="server" ID="btnGo" Text="Go" OnCommand="btnGo_Command" />
<asp:Label runat="server" ID="lblResult"></asp:Label>
</div>
</form>
</body>
</html>
<script runat="server" language="C#">
void btnGo_Command(object sender, CommandEventArgs e)
{
lblResult.Text =txtTest.Text ;
}
</script>
Aside from the previous answer you can explicitly clear it on click TextBox1.Text = ""; Or Redirect to the same page should clear everything out.
The ViewState manages the information of the current page. It is utilized by the HTML pages by ASP.NET applications to maintain the state of the web form controls. By this you can save a lot of coding by maintaining the ViewState of the objects in your Web Form.
You do not need ViewState in the following situations:
The control is repopulated on every postback. If you ignore old data, and if you repopulate the server control each time the page is refreshed then you do not need ViewState.
When you complete a web page, review the controls in the page and consider what information is being passed in the view state and whether you really need all that information to be maintained. To optimize web page size, consider disabling view state in these cases.
The control is an input control and it changes only from user actions.
The control never changes.
By default, ViewState is enabled for all server controls. ViewState can be enabled and disabled in any of the following ways:
Control Level
Page Level
Application Level
Machine Level
To disable ViewState
To disable ViewState for a single control on a page, set the EnableViewState property of the control to false, as in the following:
<asp:DropDownList ID="DropDownList1" runat="server" EnableViewState="false" />
To disable ViewState for a page
To disable ViewState for a single page, set the EnableViewState attribute in the # Page directive to false, as in the following:
<%# Page Language="C#" EnableViewState="false" AutoEventWireup="true" CodeFile="URLRouting.aspx.cs" Inherits="URL_Rewriting" %>
To disable a page's View State, add the code below in the Page class of the page.
public void DisableViewState()
{
this.Init += new EventHandler(Page_Init);
}
private void Page_Init(object sender, System.EventArgs e)
{
this.EnableViewState = false;
}
To disable ViewState for a specific application
To disable ViewState for a specific application, use the following element in the Web.config file of the application:
<configuration>
<system.web>
<pages enableViewState="false" />
</system.web>
</configuration>
To disable ViewState for all applications on a Web server
To disable ViewState for all applications on a Web server, configure the element in the Machine.config file as follows:
<Machine.config >
<system.web>
<pages enableViewState="true" />
</system.web>
</Machine.config>

Getting A page can have only one server-side Form tag Error

I have done my MasterPage and create a new .aspx page with this MasterPage . but whenever I try to add a RadioButton to the .aspx page it's generate to me this error:
Control 'head_ctl00' of type 'RadioButton' must be placed inside a
form tag with runat=server.
and I have tried to add a form tag and this error came out !
A page can have only one server-side Form tag.
I'm confused how I can solve this problem ! any idea ?
in case you need my .aspx page :
<%# Page Title="" Language="C#" MasterPageFile="~/MySite.Master" AutoEventWireup="true" CodeBehind="Registration.aspx.cs" Inherits="MyWebsite.Registration" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<form id="frm" runat="server">
<asp:RadioButton runat="server"></asp:RadioButton>
</form>
</asp:Content>
You have inserted your RadioButton inside the head placeholder that has not the form tag in your MasterPage file. You should place RadioButton in another PlaceHolder like MainContent or FeaturedContent. Also you don't need the form tag in your ContentPages, The form tag on the master page will be sufficient.

How can I get my asp:TreeView control to recognize the TreeNodeCheckChanged method I wrote?

I'm having a really frustrating issue with a TreeView control in a Web Form. I'm using C# on Visual Studio, and, admittedly, this is my first project on the platform, so there are a lot of caveats I'm finding I'm not aware of.
The page I'm working on isn't that complicated. In the body of WebPage.aspx, I have an empty TreeView control declared, along with a Label to display output (for testing) and a Button to cause a postback:
<asp:TreeView ID="SimpleTreeView" runat="server">
</asp:TreeView>
<asp:Label ID="StatusLabel" runat="server">No change yet.</asp:Label>
<asp:Button ID="SaveButton" runat="server" Text="Save Changes" PostBackUrl="~/WebPage.aspx" />
I populate the TreeView programmatically within the Page_Load method of my WebPage class, based on data in our SQL server. That part works like a charm.
Now, I want to define the event handler for the TreeView's TreeNodeCheckChanged event. Firstly, YES, I know that the event does not fire immediately when a checkbox is changed; 99% of everything I can find on the Internet about this is people complaining about that. For my application, waiting until the button is clicked is fine.
I've followed what the MSDN article on the event does, by adding the OnTreeNodeCheckChanged attribute to the TreeView control:
<asp:TreeView ... OnTreeNodeCheckChanged="CheckChangedMethod">
and added a corresponding method to the WebPage class in WebPage.aspx.cs:
protected void CheckChangedMethod( object sender, TreeNodeEventArgs e )
{
StatusLabel.Text = "A checkbox was changed!";
}
When I launch the page, though, I get an error screen that says:
CS1061: 'ASP.webpage_aspx' does not contain a definition for 'CheckChangedMethod' and no extension method 'CheckChangedMethod' accepting a first argument of type 'ASP.webpage_aspx' could be found (are you missing a using directive or an assembly reference?)
I have found that if I move the method to within a tag on WebPage.aspx, it works! Unfortunately, though, I need the method to access classes and methods in other parts of the site, which I can't from within the script tag (...right?). How can I get my event handler recognized by the compiler without removing it from the WebPage class?
Edit:
The total markup looks like this:
<%# Page Title="Web Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireUp="true" CodeBehind="WebPage.aspx.cs" Inherits="Project.WebPage" %>
<%# MasterType VirtualPath="~/Site.Master" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolKit" %>
<asp:Content ID="Content1" ContentPlaceHolder="HeadContent" runat="server">
<!-- This is where I placed the script tag to test the method -->
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolder="MainContent" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
<h2><em>Headline</em></h2>
<br />
<asp:TreeView ID="SimpleTreeView" runat="server" ExpandDepth="0" ShowCheckBoxes="All">
</asp:TreeView>
<asp:Label ID="StatusLabel" runat="server">No change yet.</asp:Label>
<asp:Button ID="SaveButton" runat="server" Text="Save Changes" PostBackUrl="~/WebPage.aspx" />
</asp:Content>
Well... Not sure what happened, but after fixing bugs elsewhere on our site, the code above magically decided to start working. I'm not going to question it.

How to access values from cached user control?

There are 2 user controls(Test1.ascx and Test2.ascx). Test1.ascx contains Test2.ascx.
The inner user control(Test2.ascx) html is:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Test2.ascx.cs"
Inherits="Test.UserControls.Test2" %>
<%# OutputCache Duration="200" VaryByParam="None" %>
<%# Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<telerik:RadTreeView runat="server" ID="radTreeView" >
<DataBindings>
<telerik:RadTreeNodeBinding Depth="0" CssClass="rootNode" />
</DataBindings>
</telerik:RadTreeView>
The outer user control(Test1.ascx) html is like:
<div runat="server" id="divTreeViewContainer">
<uc:ucTreeView runat="server" ID="ucTreeView" />
</div>
When first time the page is requested, both the user controls are loading perfectly.
The tree view from Test2.ascx is accessed by FindControl() in Test1.ascx as
//Find the tree view from the Test2.ascx user control
var radTreeView = ucTreeView.FindControl("radTreeView") as RadTreeView;
From 2nd page request on-wards(i.e after inner user control Test2.ascx is cached) the ucTreeView is coming as null.
Requirement:
The Test2.ascx user control needs to be cached and the control values of this user control will be accessed with in Test1.ascx user control(both in cached and non-cached condition). How to do it?
Lots of thanks in advance.

Locate HTML Element when it does not have the runat="server" attribute

I have an ASP.NET C# website and I am attempting to retrieve the inner html from a HTML in my page when a button is clicked.
My Problem: I use the function FindControl() but it returns null when it should find the element. Why is this happening, what am I doing wrong?
My HTML page:
<%# Page Title="test" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="test.aspx.cs" Inherits="test" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="ActualContent">
<div class="regMainContainer mainContainer container">
<!-- Attempting to get the below div -->
<!-- Knowtice it does not have runat="server",
I would prefer not to do that if I dont need to -->
<div id="courseDiv" class="courseContainer">
</div>
</div>
</asp:content>
My Code that executes when a button is clicked(inside test.aspx.cs file:
HtmlGenericControl d = (HtmlGenericControl)FindControl("courseDiv");
FindControl can only find controls that has runat="server" attributes. The good news is that you can easily change you div to a panel, and add data that way.
the bad news is that this still won't let you access the innerhtml of the div, .net sees it as just a container for other controls.
The best way to do this would be some form of ajax, since your client side script would be able to read that contents and pass it to a server side method
You won't be able to use FindControl for something that's not marked with runat="server". This is because any of the elements not marked with runat="server" get parsed as one giant text literal at runtime. You can add runat="server" to any arbitrary html element, though.

Categories