.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Object Reference Error While Rendering Menu Control

Posted By:      Posted Date: September 20, 2010    Points: 0   Category :ASP.Net

I am having a problem with rendering a menu control inside a server control. I am getting an error in the RenderContents override method when I try to render the Menu Control. The error I am getting is an Object Reference error. The code is below...

[ToolboxData("<{0}:Login runat=server></{0}:Login>")]
    public class Login : CompositeControl
        #region Members

        Label tst;
        Menu loginMenu;
        MenuItem mainLoginItem;
        MenuItem loginItem;
        MenuItem usernameItem;
        MenuItem passwordItem;
        SubMenuStyle subMnuStyleControl;
        SubMenuStyle subMnuStyleMenu;

        bool isLoggedIn = false;


        #region Properties

        public bool IsLoggedIn
            get { return isLoggedIn; }

            set { isLoggedIn = value; }


        #region Overridden Events

        protected override void RenderContents(HtmlTextWriter writer)



        protected override void OnInit(EventArgs e)

            #region Add CSS references
            string cssUrl = Page.ClientScript.GetWebResourceUrl(this.Ge

View Complete Post

More Related Resource Links

Registering controls of current assembly object reference NOT set error


Hi There,

I have created a simple ASP.net Web Application (2.0) and have added a web user control.

Now in my page I have added this control but I have registered like this,

<%@ Register Assembly="WebApplication1" Namespace="WebApplication1" TagPrefix="Custom" %>

Which means I want to access all the controls in my current Web Application project

Then I have added my user control like this,

<Custom:MyUserControl ID="MyUserControl1" runat="server" PublicProperty="Hello" />

Every thing is fine but when I execute the project, NO control on my user control gets "instantiated" and thus I receive error "Object Reference Not Set"

Note that My Control has,

1) Public property PublicProperty as String

2) 1 Label control

In Load Event Handler I am setting Text property of Label Control to PublicProperty. Here object reference NOT set error occurs (which means Label control is NOT initialized).

I don't want to register my control using Src, TagPrefix etc. Any ideas?


FileUpload error: Object reference error


I have a FormView with a FileUpload to upload an image in a database.

I keep getting an object reference error.(view code)

I am using this same script to upload the image to the database, but when I try to update the file upload I get the error.    

string strFilePath=Server.MapPath("\\images\\"+fupdImage.FileName);

        Byte[] image=null;
        HttpPostedFile imgVid=FileUpload.PostedFile;

        image=new Byte[imgVid.ContentLength];//Object reference not set to an instance of an object.

        if(FileUpload.HasFile) {
        string imageFile=FileUpload.PostedFile.FileName;
        int index=imageFile.LastIndexOf(".");
        string fileFormat=imageFile.Substring(index+1);


Menu control rendering issue with IE8



Using VS2010, I created an ASP.NET 4.0 web application and simply added a couple of menu items below the "Home" menu item in the master page that's created by the project wizard. I made no other changes - no code, no stylesheet changes.

If I run the app locally then everything is fine. I suspect because the local IIS is responsive enough for the problem not to occur.

If I deploy the app to a web host (discountasp.net) then I see the menu render vertically for less than a second before it renders correctly. If I refresh the page a few times then usually I can see the menu vertical flash but sometimes I can't, so there's some sort of timing consideration.

I'm using IE8. The problem doesn't seem to occur with either Firefox 3 or Chrome.

Have others seen this problem?

Any suggestions for a fix?

I can supply the zipped up project if anyone wants it.


Object reference error

Hi, I have an XML File shown below<?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0"> <Title>Products</Title> <link rel="self" href="http://localhost:49200/" /> <updated>30-08-2010T04:17:45Z</updated> <author> <id>tag:localhost,30-8-2010:/support/products</id> <entry> <id>13137</id> <title>example</title> </entry> </author> </feed> I am trying to read the id tag in the entry tags but i get object reference not set to ............. error the code to read it isDim prddoc As New XmlDocument prddoc.Load(Server.MapPath("prd.xml")) Dim xmlList As XmlNodeList = prddoc.GetElementsByTagName("entry") Dim rootNode As XmlElement rootNode = prddoc.DocumentElement For ic As Integer = 0 To xmlList.Count - 1 response.write(prddoc.SelectNodes("//entry/id").Item(0).InnerText Nextthe error is on line response.write(prddoc.SelectNodes("//entry/id").Item(0).InnerTextplz help  

Error "Object reference not set" when I try to set a Navigation Property

I'm using Entity Framework. The following code throws a runtime error "System.NullReferenceException: Object reference not set to an instance of an object." The line before the error, it looks like newControl is in fact instantiated.My model has a Control entity and a ControlType entity. Control includes the Navigation Property "ControlType." I'm trying to set ControlType.Type = 2.SurveyFormControlsModel.Control newControl = new SurveyFormControlsModel.Control(); newControl = CreateControl(childTokenName, ControlTypeEnum.TextBox); newControl.ControlType.Type = 2; // <<--ERROR HERE context.Controls.AddObject(newControl);                                SurveyFormControlsModel.Control newControl = new SurveyFormControlsModel.Control();                                 if (listItems.Count == 0)                                 {                                     newControl = CreateControl(childTokenName, ControlTypeEnum.TextBox);                    &

Object reference not set to an instance of an object error.

i've installed the VSeWSS.msi on VS 2005, i'm using SPS 2007, i'm developing on my workstation in C#, i've added the Mircosoft.Sharepointserver dll reference to my project but i still can't deploy a very basic webpart. i get the "Object reference not set to an instance of an object" error but there's no reference to a line, column, project or anyhting. very frustrating. any suggestions/links whould be appreciated.

Login error - Object reference not set to an instance of an object.

Hi all,I've set up the login section as a user control. WheneverI log in I get a "Object reference not set to an instance of an object", with the code stopping on this line: if (Membership.ValidateUser(txtUserName.Text,txtPassword.Text))Can anyone tell me how to fix this please?protected void LoginButton_Click(object sender, EventArgs e) { TextBox txtUserName = loggedin.FindControl("UserName") as TextBox; TextBox txtPassword = loggedin.FindControl("Password") as TextBox; CheckBox ckbRememberMe = loggedin.FindControl("RememberMe") as CheckBox; if (Membership.ValidateUser(txtUserName.Text,txtPassword.Text)) { FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, ckbRememberMe.Checked); } else { // Msg.Text = "Login failed. Please check your user name and password and try again."; } } <asp:LoginView ID="loggedin" runat="server"> <AnonymousTemplate> <asp:Login ID="Login1" runat="server"> <LayoutTemplate> <table id="mainbox" width="400"> <tr> <td width="150" class="label">

Strange Repeater Error, Object reference not set, Label not visible etc etc..

Hi Everyone,This is very strange and as of yet I cant seem to get round it, although it is a somewhat easy error to identify it is however becoming very annoying as everything I try doesn't seem to work...The repeater displays results for upcoming subscribers birthdays and after their day and month ("dd/mm/") I have a label to display the current year. This causes the old error of: Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.Source Error:  Line 55: Label lblYear = e.Item.FindControl("lblYear") as Label;Line 56: Line 57: lblYear.Text = DateTime.Now.Year.ToString();Line 58: }Line 59: As you can see the object is set correctly - The ASPX is below, for saving time on reading etc I've posted the repeater script only and not the whole page, although I can do if needs be.I've tried a number of things with subtle differences but to no avail: with Literal, same error - Tried inserting the year directly via <%#((system.datetime).now.year.tostring())%> or something to that effect, this also doesnt

Error while export to pdf-Object reference not set to an instance of an object

Hello, I am getting error while rendering the report to pdf in SSRS 2008. This is happening randomly and sometimes I get this error. I have SQL Server 2008 SP1 installed in my system . I installed the cumulative update 1 for SP1 also but no luck. Every time when export to pdf fails, SSRS is creating the dump file in the logs. I have captured the log of this specific error. Please let me know if you have any idea about this.   reportrendering!ReportServer_0-297!1ec4!03/30/2010-10:32:57:: e ERROR: Throwing Microsoft.ReportingServices.ReportProcessing.UnhandledReportRenderingException: An error occurred during rendering of the report., ; Info: Microsoft.ReportingServices.ReportProcessing.UnhandledReportRenderingException: An error occurred during rendering of the report. ---> Microsoft.ReportingServices.OnDemandReportRendering.ReportRenderingException: An error occurred during rendering of the report. ---> System.NullReferenceException: Object reference not set to an instance of an object.   at Microsoft.ReportingServices.Rendering.HPBProcessing.Paragraph.get_SpaceBefore()   at Microsoft.ReportingServices.Rendering.RichText.LineBreaker.FlowParagraph(Paragraph paragraph, Directions direction, IntPtr hdc, Single dpiX, FontCache fontCache, FlowContext flowContext, Boolean keepLines, SizeF flowContextSize, Int32& contentOffset)   at Mi

Help with Object reference not set to an instance of an object. error.

I was given a chunk of code to help with accessing dynamic forum controls about a week back and when I implemented the code I get the error "Object reference not set to an instance of an object". I asked in the thread the code was given but have not recived an answer yet (asked about 4 days ago) and I think that is beause  the thread is marked as resolved. The line of code  causing the error is   if(t.Equals(this.ddlAmountToAdd.ClientID)&&!string.IsNullOrEmpty(v))    And here is the full code for the c# .Net 4 page.using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class GameInformation_AddUpcomingRelease : System.Web.UI.Page { public string[] Regions = { "USA", "Japan", "Europe", "Other" }; //Create a string array of regions. public string[] Platforms = { "PlayStation 3", "X-Box 360", "Wii", "Computer", "PSP", "Other" }; //Create a string array of platforms. protected void Page_Load(object sender, EventArgs e) { ddlPlatform1.DataSource = Platforms; ddlPlatform1.DataBind(); ddlRegion1.DataSource = Regions; ddlRegion1.DataBind(); } protected override void OnInit(EventArgs e)

Configure managed accounts - object reference not set to an instance of an object - error

I was working in central admin and activated the managed accounts password change for the farm account with the option to change the password now.  I got the email notification that the password was changed and it seems in the log files that it did update all the credentials that were used with the account.  Problem is now that when I hit the configure managed accounts link in central admin all I get is the error: Error Object reference not set to an instance of an object.  Troubleshoot issues with Microsoft SharePoint Foundation. Correlation ID: c6dc7a46-894f-4b85-8711-8af1e8ec7903 Date and Time: 8/23/2010 9:20:20 AM Added information from logs: 08/23/2010 10:41:33.24  w3wp.exe (0x0F2C)                        0x07FC SharePoint Foundation          Logging Correlation Data       xmnv Medium   Name=Request (GET:http://cmtcalcium:33333/_admin/ManagedAccounts.aspx) b9fae5a9-7405-407d-87fc-239dc0ff59d0 08/23/2010 10:41:33.24  w3wp.exe (0x0F2C)                        0x07FC SharePoint Foundation     &n

Giving me an error "Object reference not set to an instance of an object."

Hello Everyone, I am currently developing a website for online examination.  For that I have to collect user information at the time of registration. I want to develop a 3-tier application. I have SignUpWizard. Aspx page. I have also created 3 classes (Users.cs, UserDAL.cs and UserBAL.cs) and 1 stored procedure (InsertUserInfo).Code for Users.cs:using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data.SqlClient; using System.Web.Security; using System.Data; namespace ITIL.DomainModels { public class Users { public int UserID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Username { get; set; } public string Password { get; set; } public string EmailAddress { get; set; } public string dateTime { get; set; } public string IPAddress { get; set; } public string SecurityQuestion { get; set; } public string SecurityAnswer { get; set; } } }Code for UserDAL.cs:using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; using System.Configuration; using ITIL.DomainModels; namespace ITIL.DAL { public class UserDAL { publi

Site Manager Error object reference error line 145 SiteManager.aspx SmtPostBackHandler1.UniqueID

Hi I am getting error bellow irrespective of if its IE or firefox Server Error in '/' Application. Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: Line 143: Line 144: Line 145: <a onclick='javascript:__doPostBack("", "Refresh=<%= TreeView1.SelectedNode.Value %>")' style="cursor:pointer"> Line 146: <SharePoint:EncodedLiteral runat="server" text="<%$Resources:cms, SmtRefreshLink%>" EncodeMethod='HtmlEncode'/> Line 147: Source File: c:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\SiteManager.aspx Line: 145 Stack Trace: [NullReferenceException: Object reference not set to an instance of an object.] Microsoft.SharePoint.Publishing.Internal.WebControls.ObjectSerializer.get_WebServerRelativeUrl() +148 Microsoft.SharePoint.Publishing.Internal.WebControls.ObjectSerializer.get_CachedList() +149 Microsoft.SharePoint.Publishing.Internal.WebControls.ObjectSerializer.get_AutomationId() +178 Microsoft.SharePoint.Publishing.Internal.WebContro

error rendering control


Hi, I am working with VS 2008, I created a usercontrol to select dates, when I put It into my web pages inside an UpdatePanel and all seem to be ok, but suddenly I got the Error Rendering Control, I don´t understand it?  

SqlCommand error: "Object reference not set to an instance of an object."


 Hi all,

I am not sure what's wrong with this block of code:

  • protected void FillDataGridView(string timeStamp)   
  • {   
  •  string select = "exec Uds.Dashboard_GetJobs";   
  •  string connectionString = WebConfigurationManager.ConnectionStrings["UctConnectionString"].ConnectionString;            
  •  SqlDataSource sourceRealtimeLogging = new SqlDataSource(connectionString, select);   
  •  SqlCommand cmd = new SqlCommand();   
  •  cmd.CommandType = CommandType.StoredProcedure;   
  •  cmd.Parameters.Add(new SqlParameter("@date", SqlDbType.DateTime));   
  • Object reference not set to an instance of an object in Nested Repeater Control of CheckBox List con

     if ((item.ItemType == ListItemType.Item) || (item.ItemType == ListItemType.AlternatingItem))
                    Repeater rptsub = (Repeater)item.FindControl("rptsub");
                    CheckBoxList Chksub = (CheckBoxList)rptsub.FindControl("Chksub");
                    Label lblsubroot = (Label)rptsub.FindControl("lblsubroot");
                    DataRowView row = (DataRowView)e.Item.DataItem;
                    RootId = Convert.ToInt32(row["IdApplication"].ToString());
                    MetadataPermissions metadataPermissions = new MetadataPermissions(); ;
                    DataSet rptRootValues = new DataSet();
                    rptRootValues = metadataPermissions.GetrptSubMenus(RootId);
                    DataRow[] drows = rptRootValues.Tables[0].Select("IdApplicationroot = " + row["IdApplication"].ToString());
                    foreach (DataRow chkpermsns in drows)
                       ListItem li = new ListItem(chkpermsns["PermissionName"].ToString());
    <asp:Repeater ID="rptroot" runat="server" OnItemDataBound="rptroot_ItemDataBound">

    Rendering A Menu Control To A String


     Hi all,
    coud someone please tell me why the following code bombs with a NullReference exception.

            Dim m As New Menu
            Dim mi As New MenuItem("First")
            Dim sb As New StringBuilder
            Dim html As String
            Using sw As StringWriter = New StringWriter(sb)
                Using tw As HtmlTextWriter = New HtmlTextWriter(sw)
                End Using
            End Using
            html = sb.ToString

    I just want to output the html for the menu control to a string, if I remove the line that adds the new menu item or I change the control to a calander control instead of a menu control the it works fine.

    ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
    Sql Server  SharePoint  Silverlight  Others  All   

    Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend