Visible on FindControl not working - asp.net - c#

I'm getting "Object reference not set to an instance of an object" exception, on the next line of code:
((HyperLink)Page.FindControl(id)).Visible = false;
What can be the problem?
Here is a sample from my code:
.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="FriendsList.aspx.cs" Inherits="Private_User_Social_FriendsList" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<div class="FriendsProposal" runat="server">
<div class="FriendsProposal_Header">FriendsP</div>
<div id="FriendsProposalPH" class="FriendsProposalPH" runat="server"></div>
.aspx.cs:
public partial class Private_User_Social_FriendsList : System.Web.UI.Page
{
DBservices DBS = new DBservices();
protected void Page_Load(object sender, EventArgs e)
List<Friends> ListFriendsProposal = DBS.getFriendsProposal(User.Identity.Name.ToString());
foreach (Friends FRIndex in ListFriendsProposal)
{
string _FriendsOutput = FR_output(FRIndex);
HyperLink tempHL = new HyperLink();
tempHL.Text = _FriendsOutput;
tempHL.CssClass = "HyperLinkFriends";
tempHL.ID = FRIndex.UdName;
FriendsProposalPH.Controls.Add(new LiteralControl("<div style='height:32px' runat='server' >"));
FriendsProposalPH.Controls.Add(tempHL);
Button tempApprove = new Button();
tempApprove.Text = "Approve";
tempApprove.Click += new EventHandler(cmdUpdate_Click);
tempApprove.ID = FRIndex.UdName + "1";
FriendsProposalPH.Controls.Add(tempApprove);
FriendsProposalPH.Controls.Add(new LiteralControl("</div>"));
}
}
private void cmdUpdate_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string _tempID = btn.ID;
string id = _tempID.Substring(0, _tempID.LastIndexOf('1'));
DBS.ApproveFriend(User.Identity.Name.ToString(), id);
btn.Visible = false;
((HyperLink)Page.FindControl(id)).Visible = false;
}

Since you're adding the hyperlink to the FriendsProposalPH naming container (which is a placeholder control I presume) rather than the Page naming container, you should invoke the search method on that naming container and not the page itself (this method only searches within current naming container).
Judging by the code you provided the hyperlink is always added alongside the button, so perhaps the easiest way to access the right naming container and find and hide the hyperlink control is this:
btn.NamingContainer.FindControl(id).Visible = false;

your control that you are trying to find must have a runat="server" attribute or the exact same exception u receive is thrown.
dont forget that asp.net is request-response system, you cant access from the server a client-side controls.
if a control is not running at server, you cannot change it after client received it to his browser.

Related

This operation requires the page to be asynchronous (the Async attribute must be set to true).

I'm trying to execute an asynchronous task on my Azure hosted webpage inside the Page_Load method. However I'm getting the above error. I have set the Async property of the page to true in the aspx file and still no luck.
ASP Header Code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SalesAndCCFAQ.FAQ" Async ="true"%>
Page_Load Code:
protected void Page_Load(object sender, EventArgs e)
{
RegisterAsyncTask(new PageAsyncTask(test));
Page.ExecuteRegisteredAsyncTasks();
//Only need to fill catDropDown when the page is first directed to
if (!Page.IsPostBack)
{
fillCatDropDown();
//Show who is currently logged in
currentUserLabel.Text += HttpContext.Current.User.Identity.Name;
}
if (GlobalUse.external == true)
{
whichApproved = "approvedExternal = 1";
greenKeyImage.Visible = false;
greenKeyLabel.Visible = false;
yellowKeyImage.Visible = false;
yellowKeyLabel.Visible = false;
redKeyImage.Visible = false;
redKeyLabel.Visible = false;
}
else
{
whichApproved = "approvedInternal = 1";
}
//String to be added to main query if a category is selected
filterCatQuery = "cid = (SELECT cid FROM Category WHERE name = '" + catDropDown.Text + "')";
}
Page_PreInit Code:
protected void Page_PreInit()
{
if (!Page.IsPostBack)
{
if (GlobalUse.external == true)
{
this.MasterPageFile = "~/SiteExternal.Master";
}
}
}
Asynchronous function that is called:
protected async Task test()
{
if (GlobalUse.external != null)
return;
await GlobalUse.isUserExternalGroup(); //This method sets GlobalUse.external
Response.Redirect("~/Default.aspx"); //Refresh to call the PreInit Code again
}
Set Async to true as below in the page.
<%# Page Title="" Language="C#" Async="true" MasterPageFile="~/XXX.Master" AutoEventWireup="true"
CodeBehind="XXX.aspx.cs" Inherits="XXX"
ValidateRequest="false" meta:resourcekey="XXX" %>
The reason this error was being thrown is because it was my Default page. The way I fixed it was by creating a blank Default page which then redirects to my desired homepage upon it being loaded. I will leave this here as it may be of use to someone and I believe it is quite a unique case.
You can write this.AsyncMode = true; under page load to allow Async tasks execution.

Not able to access master page control

I have this in my Master page:
<asp:ContentPlaceHolder ID="BannerPlaceHolder" runat="server">
<asp:HyperLink ID="PortalBanner" runat="server"
ImageUrl="Images/banner-12-5-11.jpg"
NavigateUrl="~/Default.aspx"></asp:HyperLink>
</asp:ContentPlaceHolder>
I want to be able to change the hyperlink ImageUrl but I get a null exception:
Object reference not set to an instance of an object.
Here's my code to access the HyperLink
ContentPlaceHolder cp = (ContentPlaceHolder)this.Master.Master.FindControl("BannerPlaceHolder");
HyperLink hp= (HyperLink)cp.FindControl("PortalBanner");
Are you sure that it is in the Master of the Master? If not, simply change it to:
ContentPlaceHolder cp = (ContentPlaceHolder)this.Master.FindControl("BannerPlaceHolder");
Another approach is to provide a property in your master that you can access from your page by casting it to the actual type.
in the master's codebehind:
public string PortalBannerImageUrl
{
get {
return this.PortalBanner.ImageUrl;
}
set {
this.PortalBanner.ImageUrl = value;
}
}
in the page:
var myMaster = this.Master as YourMasterType;
if(myMaster != null)
{
myMaster.PortalBannerImageUrl = newImageUrl;
}

SelectedIndexChanged Event not firing under any circumstances

As the title says I am experiencing a problem where the SelectedIndexChanged Event of a drop down list will not fire under any circumstances. I have spent several hours looking for the solution and trying different things. Some places suggest that this is a known bug and provide work-arounds but none of them have worked for me up until this point.
The drop down in question is built here:
<tr>
<td>
Select Project
</td>
<td>
<asp:DropDownList ID="ddlProjects" runat="server"
OnSelectedIndexChanged="ddlProjects_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
</tr>
This seems standard enough to me so I do not know where it could be going wrong.
EDIT (sorry I am new to this):
Code Behind:
protected void ddlProjects_SelectedIndexChanged(object sender, EventArgs e)
{
List<DashBoardImport> selectedProject = DBI.GetProject(Convert.ToInt32(ddlProjects.SelectedValue));
foreach (var proj in selectedProject)
{
txtProjectName.Text = proj.ProjectName;
this.ddlStatus.SelectedIndex = proj.Status.Equals("Current") ? 0 : 1;
var priority = proj.Priority.PriorityName;
if (priority.Equals("Low"))
{
ddlPriority.SelectedIndex = 0;
}
else if (priority.Equals("Medium"))
{
ddlPriority.SelectedIndex = 1;
}
else if (priority.Equals("High"))
{
ddlPriority.SelectedIndex = 2;
}
//txtRank.Text = proj.ProjectRank.ToString();
txtBusinessArea.Text = proj.BusinessArea.BusinessAreaName;
txtRequester.Text = proj.Requestor;
}
//selectedIndex.Value = ddlProjects.SelectedIndex.ToString();
}
There is no javascript even touching this function in anyway. I have removed it to try and take things back to basics so to speak. I have put break points in the page_load in the onselectedindexchanged function and in several other places and the event is never fired and the selected index is never changed from 0.
Edit2:
Here is the code several people have asked for.
<%# Page Title="Future Projects" Language="C#" MasterPageFile="~/Site.Master" EnableEventValidation="true"
AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ITDashBoard.Web.Default" %>
Add AutoEventWireup="true" to your page in given below line like this
<%# Page Language="C#" AutoEventWireup="true" .................. %>
Edited: then add your own event handler
ddlPojects.SelectedIndexChanged += new EventHandler(ddlPojects_SelectedIndexChanged);
Your code behind and the .aspx code looks fine. What I suspect is a namespace issue.
Can you post up your page directive (this bit in your aspx page <%# Page Language="C#" .....). Specifically I want to see the inherits attribute. I also need to the the namespace of the .cs class where protected void ddlProjects_SelectedIndexChanged(object sender, EventArgs e) resides.
Have you also tried adding a break point in the ddlProjects_SelectedIndexChanged to see if it get hit?

ASP.net get content page to change master page control

Master page:
<form runat="server">
<Scirra:MainMenu runat="server" ID="MainMenu" TopTabSelected="home" SubTabSelected="link2" />
<asp:ContentPlaceHolder id="MainContent" runat="server">
snip
Content page:
Master.MainMenu.TopTabSelected = "forum";
I know I'm probably doing this wrong, but is this possible? I want to change a parameter of that control. It says 'inaccessible due to protection level'.
You should provide a public property f.e MenuTabSelected in your MasterPage that Gets/Sets this property of your Menu.
public string MenuTabSelected {
get { return MainMenu.TopTabSelected; }
set { MainMenu.TopTabSelected = value; }
}
Then you can access it in this way:
((YourMasterPage)Master).MenuTabSelected = "forum";
where YourMasterPage is the type of your MasterPage.
The compiler error is thrown because you want to access a private or protected control from outside of your MasterPage-Class. This would only be allowed if it would be public, what is not recommended. You have more control if you do it the way i suggested :)
find menu items in content page and change its value
protected void Page_Load(object sender, EventArgs e)
{
Menu mainMenu = (Menu)Page.Master.FindControl("NavigationMenu");
MenuItem menuMaterials = mainMenu.FindItem("Materials");
if (menuMaterials.Value == "Materials")
{
menuMaterials.Value = "NO materials";
menuMaterials.Text = "No materials";
}
}

Accessing RadEditor control from master page's code behind...its not finding any radEditor control when it is there..whats wrong?

Its not executing statements in if block in my method
Master Page:-
page load event:-
Control c = new Control();
DoSomething(c);
My method:-
protected void DoSomething(Control control)(
{
foreach (Control c in control.Controls)
{
if(typeof(c).Equals(Telerik.Web.UI.RadEditor))
{
Telerik.Web.UI.RadEditor rad = c as Telerik.Web.UI.RadEditor;
label1.Visible = true; label1.Text = "dhchk";
rad.CssFiles.Add("~/styles/myStyle.css");
rad.CssFiles.Add("~/styles/myStyle2.css");
rad.CssFiles.Add("~/styles/myStyle3.css");
}
else
{
DoSomething(c);
}
}
}
my content page:-
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<telerik:RadEditor ID="Editor1" EnableEmbeddedBaseStylesheet="false" EnableEmbeddedSkins=false runat="server">
</telerik:RadEditor>
<telerik:RadEditor ID="Editor2" EnableEmbeddedBaseStylesheet="false" EnableEmbeddedSkins=false runat="server">
</telerik:RadEditor>
[EDIT] ok when debugging..I rt clicked "c" and then Quick watch...it says "The name 'c' does not exist in the current context" (?!?!) how so ?
Well, the Master page renders first so you won't have access from the master page to any of the content page controls. You can achive this using events and passing the control from the content to the master
udpate:
Again - Accessing user controls from the master page is flaw in the whole master->content design. the closest thing I can imagine is adding static function
public static void AddDesign(RadEditor obj)
{
...
}
and then call the function form the Page_Load of the user control
MASTER_PAGE_CLASS_NAME.AddDesign(RadEditor1);
Well, I'm not sure, you can access controls in page like this.
At first: that editor should be probably in some Panel (or some other container), so i should look like this:
<asp:Panel ID="pnl1" runat="server">
<telerik:RadEditor ID="Editor1" EnableEmbeddedBaseStylesheet="false" EnableEmbeddedSkins=false runat="server" />
<telerik:RadEditor ID="Editor2" EnableEmbeddedBaseStylesheet="false" EnableEmbeddedSkins=false runat="server" />
</asp:Panel>
Then try this:
protected void Page_Load(object sender, EventArgs e)
{
foreach (Controls c in pnl1.Controls)
{
if (c is Telerik.Web.UI.RadEditor)
{
// do you stuff ...
}
}
}
You should change things around and call your MasterPage method from the content control.
In your masterpage add the method:
public void DoSomething(Telerik.Web.UI.RadEditor rad)
{
label1.Visible = true; label1.Text = "dhchk";
rad.CssFiles.Add("~/styles/myStyle.css");
rad.CssFiles.Add("~/styles/myStyle2.css");
rad.CssFiles.Add("~/styles/myStyle3.css");
}
Call the function from an appropriate event in your page/content control. eg Page.Load, Editor1.Load etc
Master.DoSomething(Editor1);
Update
From the masterpage, you should search for child controls in the Content controls
ContentPlaceHolder1.FindControl("Editor1");
or you could try something like:
foreach (Control c in ContentPlaceHolder1.Controls)
{
if(typeof(c).Equals(Telerik.Web.UI.RadEditor))
{
Telerik.Web.UI.RadEditor rad = c as Telerik.Web.UI.RadEditor;
label1.Visible = true; label1.Text = "dhchk";
rad.CssFiles.Add("~/styles/myStyle.css");
rad.CssFiles.Add("~/styles/myStyle2.css");
rad.CssFiles.Add("~/styles/myStyle3.css");
}
else
{
DoSomething(c);
}
}
The load and render events of the master page are fired after those of the content page (as said here). Hence the controls in the content page should be available by the time these two events are fired?

Categories

Resources