Control is null when used nested master pages - c#

I have a simple hierarchy of nested master pages.
However, in runtime, the master page controls (exemplified by label1) are always null.
If Default.aspx is changed to use Base.master directly, the master page controls will be correctly defined.
What is the cause for this behavior?
Base.master
<%# Master Language="C#" CodeFile="Base.master.cs" Inherits="BaseMaster" %>
<!DOCTYPE html>
<html lang="en">
<head runat="server"></head>
<body>
<form runat="server">
<asp:Label runat="server" id="label1" Text="Label 1" />
<asp:ContentPlaceHolder runat="server" ID="MainContent" />
</form>
</body>
</html>
Base.master.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class BaseMaster : MasterPage
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
label1.Text = "Base"; // Causes NullReferenceException
}
}
Sub.master
<%# Master Language="C#" CodeFile="Sub.master.cs" Inherits="SubMaster" MasterPageFile="~/Base.master" CodeFileBaseClass="BaseMaster" %>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<asp:ContentPlaceHolder runat="server" ID="SubMainContent" />
</asp:Content>
Sub.master.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SubMaster : BaseMaster
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
label1.Text = "Sub"; // Causes NullReferenceException
}
}
Default.aspx
<%# Page Language="C#" CodeFile="Default.aspx.cs" Inherits="DefaultPage" MasterPageFile="~/Sub.master" %>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="SubMainContent">
<h3>Default</h3>
</asp:Content>
Default.aspx.cs
using System;
using System.Web;
using System.Web.UI;
public partial class DefaultPage : Page
{
}

Related

asp using master page variable in content page

I've read every post I can find on how to do this and tried them all. I have a Master page called DNAStaff (at root) containing:-
<%# Master Language="C#" AutoEventWireup="true" CodeFile="DNAStaff.master.cs" Inherits="DNAStaff" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link href="~/Styles/DNA.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
...............
</div>
</form>
</body>
</html>
The Masterpage code behind includes:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Data;
public partial class DNAStaff : System.Web.UI.MasterPage
{
public string MyAccessLevel
{
get; set;
}
protected void Page_Load(object sender, EventArgs e)
{
string ConnectionString = "Data Source=NZ1;Initial Catalog=Intranet;Integrated Security=false;UID=IntranetAccess;PWD=*****";
string sqlstring = #"select [MenuID], [Item], Target, SecLevel from [MENUS] ";
SqlConnection conn = new SqlConnection(ConnectionString);
SqlDataReader rdr = null;
int MainGroup;
try
{
if (Request.Cookies["userinfo"] != null)
{
MyAccessLevel = Server.HtmlEncode(Request.Cookies["userinfo"]["accessLevel"]);
}
else
{
MyAccessLevel = "1";
}
.........
The content page includes:
<%# Page Title="" Language="C#" MasterPageFile="~/DNAStaff.master" AutoEventWireup="true" CodeFile="main.aspx.cs" Inherits="main" %>
<%# MasterType virtualpath="~/DNAStaff.master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
Set Primary Project
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:Content>
enter code here
and the content page code behind contains:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class main : System.Web.UI.Page
{
string AccessLevel = "";
protected void Page_Load(object sender, EventArgs e)
{
AccessLevel = Master.MyAccessLevel;
TextBox1.Text = AccessLevel;
}
}
The line "AccessLevel = Master.MyAccessLevel" gives an error:-
Error CS1061 'MasterPage' does not contain a definition for
'MyAccessLevel' and no extension method
'MyAccessLevel' accepting a first argument of type 'MasterPage' could be
found (are you missing a using directive or an assembly reference?)
8_Live_main.aspx D:\Development\dnanew.steelpencil.com\Live\main.aspx.cs
13 Active
I want to set the variable MyAccessLevel in the MasterPage at load and read it in any content page. I'm obviously missing something, can someone please help?
You can access the Master Page like this.
Site1 master = ((Site1)(Page.Master));
TextBox1.Text = master.AccessLevel;
Where Site1 is the class name of the Master Page (public partial class Site1 : System.Web.UI.MasterPage)
However you should know that the Master Page_Load is initialized at a later stage in the Page Life Cycle than the Page. So when you access the value of AccessLevel, it will always be empty.
See https://msdn.microsoft.com/en-us/library/dct97kc3.aspx
As in the content page already you have assigned the MasterType like below.
<%# MasterType virtualpath="~/DNAStaff.master" %>
So now your child/content page can able to use/access the master layout including the public variable/properties defined in the master page.
So now, as per your requirement, to access the public property(AccessLevel) defined in your master page and assign to the child/content page textbox, you need to write the below code
Site myMaster = ((Site)(Page.Master));
TextBox1.Text = myMaster .AccessLevel;
Hope it solves your problem.
Here are the more references about Master page and accessing the contents of master page
https://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx
https://msdn.microsoft.com/en-us/library/xxwa0ff0.aspx
This post should answer your question.You must add
<%# MasterType VirtualPath="~/your page path" %>
directive to your page

Webform not allowed because it does not extend Class

I have a very simple (currently) 1 page aspx website. It fails to compile with a message that I have not seen before. All other examples all seem to refer to master pages, which I do not have.
"Parser Error Message: 'Options.WebForm1' is not allowed here because it does not extend class 'System.Web.UI.Page'.
Source Error:
Line 1: <%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Options.WebForm1" %>
Line 2:
Line 3:
Here is the top of Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="Options.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
And for Default.aspx.cs
namespace Options
{
public partial class _Default : Page
{
What is Options.WebForm1 in <%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Options.WebForm1" %>
It should look like this if you are using a namespace
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Options._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:GridView runat="server" ID="grdTest"></asp:GridView>
</div>
<asp:TextBox runat="server" Id ="callfmptxt"/>
</form>
</body>
</html>
Code Behind-
using System;
using System.Web.UI;
namespace Options
{
public partial class _Default : Page
{
private double callfmp = 0;
public double BlackScholes(string CallPutFlag, double S, double X, double T, double r, double v) { return 0.0;}
protected void allfmptxt_TextChanged(object sender, EventArgs e) { }
}
}

ASP.NET ListBox Trouble

Here is all my code:
Site.Master
<%# Master Language="C#" AutoEventWireup="true"
CodeBehind="Site.master.cs" Inherits="WebApplication1.SiteMaster" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form runat="server">
<div class="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server"/>
</div>
</form>
</body>
</html>
Site.Master.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class SiteMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
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:ListBox ID="ListBox1" runat="server"></asp:ListBox>
</asp:Content>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ListBox ListBox1 = new ListBox();
ListBox1.FindControl("ListBox1");
ListBox1.Items.Add(new ListItem("Hello"));
}
}
}
Question: Why is my ListBox not populating?
When running the code I get a page with a small box that is completely empty.
I tried the following already and I will tell you the result -
Remove
ListBox ListBox1 = new ListBox();
ListBox1.FindControl("ListBox1");
Result: The name 'ListBox1' does not exist in the current context
Add a reference to ListBox1 manually into the designer.
Result: Object reference not set to an instance of an object.
To fix that error adding the line ListBox ListBox1 = new ListBox(); works, but still does not display.
Any ideas? Thanks.
You should only need...
protected void Page_Load(object sender, EventArgs e)
{
ListBox1.Items.Add(new ListItem("Hello", "H"));
}
See this link too
EDIT: Same code works for me.
To directly answer your question of why ListBox1 isn't getting populated:
protected void Page_Load(object sender, EventArgs e)
{
ListBox ListBox1 = new ListBox(); //You are creating a new local ListBox named ListBox1.
ListBox1.FindControl("ListBox1"); //You are trying to find the Control named ListBox1 that is held within the Control ListBox1 (and not doing anything with the result of the search)
ListBox1.Items.Add(new ListItem("Hello")); //You are adding a new ListItem to the local ListBox1.
}
As christiandev said, you should just be able to do this:
protected void Page_Load(object sender, EventArgs e)
{
ListBox1.Items.Add(new ListItem("Hello"));
}
I have no idea why you can't seem to access the ListBox1 on the aspx page.

Dynamic IDs on asp:TextBox?

This is my code, on a .ascx page :
<% for (int i = 1; i <= 10; i++)
{ %>
<asp:TextBox ID="myTextBox_<%=i %>" runat="server" Width="100%" CssClass="focus_out reset_content"></asp:TextBox>
<% } %>
but I get myTextBox_<%=i %> is not a valid identificator. So, how can I put "Dynamic IDs"?
You need to create a container for the textboxes, such as a Panel control, and then use the Page_Load in the code behind to loop through and add the text boxes to the panel.
Example:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="pnlContainer" runat="server" />
</div>
</form>
</body>
</html>
Code behind:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 1; i <= 10; i++) {
TextBox txtNewTextBox = new TextBox();
txtNewTextBox.ID = "myTextBox_" + i;
pnlContainer.Controls.Add(txtNewTextBox);
}
}
}
Here is the link for Dynamically adding textbox control in ASP.Net. Hope it works for you.

Ajax autocomple extender from a database

I want to create a textbox (for entering names) in my aspx application which suggests names of Employees from database.
I am pasting my code below. I am using Mysql
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<asp:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server"
ServiceMethod="GetCompletionList2" TargetControlID="TextBox1"
UseContextKey="True">
</asp:AutoCompleteExtender>
</div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</form>
</body>
</html>
Default.aspx.cs:
// here we use a readymade class for database operations to Mysql server
using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Gbs.DAL; // for ..redymade class..
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList2(string prefixText, int count, string contextKey)
{
myDb db = new myDb();// its class in Dal.cs
string sql = "Select * from empdata Where empname like #prefixText";
DataTable dt = db.getDataTable(sql); // method in redymade class
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["empname"].ToString(), i);
i++;
}
return items;
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
}
// there is no any error, the program runs successfully
AutocompleteExtender needs an .asmx web service which can be called from javascript.
It won't work from your Default.aspx.

Categories

Resources