3

I'm having some issues with a usercontrol. I have been at it for many hours, so have to ask for help now.

If I call the user control from the mark-up page like this:

<uc7:MenuMain2 ID="MenuMain2" runat="server" RootCategoryId="4" ImageHeight="40"
                        ImageWidth="260" />

it works fine.


I can also call it with:

Control cont = LoadControl(@"../usercontrols/MenuMain2.ascx");
ContentPlaceHolder1.Controls.Add(cont );

and that works fine too. But then I don't get to set the properties like I need too.


But if I call it to a placeholder like the code in the code below, it's not working. I'm getting the error I have posted at the bottom of the page.

Usercontrol code file - MenuMain.ascx.cs:

public partial class MenuMain2 : System.Web.UI.UserControl {

 public int ActiveCategoryId { get; set; }
 public int RootCategoryId { get; set; }
 public int articleID = 0;
 public int ImageWidth ;
 public int ImageHeight ;

  protected void Page_Load(object sender, EventArgs e) {
        if (!Page.IsPostBack)
            BindData();
    }

    private void BindData() {
        CategoriesService catSvc = new CategoriesService();
        if (ActiveCategoryId == 0) {
            if (articleID > 0) {
                M02ArticlesService artSvc = new M02ArticlesService();
                List<M02ArticlesEntity> artList = artSvc.FindById(articleID);
                if (artList.Count > 0)
                    ActiveCategoryId = artList.First().CategoryId;
            }
        }
        List<CategoriesEntity> catList = new List<CategoriesEntity>();
        catList = catSvc.GetPublishedByParentCategoryId(RootCategoryId);
        ViewState.Add("ActiveCategoryId", ActiveCategoryId);
        Repeater1.DataSource = catList;
        Repeater1.DataBind();
    }
}

Code-behind for the Masterpage:

        public HttpCookie authCookie;
        public FormsAuthenticationTicket ticket;
        private string name;
        private MenuMain2 mn;

        protected void Page_Load(object sender, EventArgs e)
        {
            mn = new MenuMain2 {RootCategoryId = 4,ImageHeight = 100, ImageWidth = 260}
            //Control cont = LoadControl(@"../usercontrols/MenuMain2.ascx");

            if (Request.Cookies[".ASPXAUTH"] != null)
            {
                authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                ticket = FormsAuthentication.Decrypt(authCookie.Value);
                name = ticket.Name;
            }

            if (name != null)
            {
                if (name.Equals("Jhon"))
                {
                    mn.RootCategoryId = 1;
                }
                if (name.Equals("Bob"))
                {
                    mn.RootCategoryId = 2;
                }
                if (name.Equals("Tom"))
                {
                    mn.RootCategoryId = 3;
                }
            }

            ContentPlaceHolder1.Controls.Add(mn);
            CategoriesEntity cat;
            int catId = Request.GetCategoryId();

            if (catId > 0)
            {
                cat = new CategoriesService().GetById(catId);
                if (cat != null && cat.RequireLogin && Request.Url.LocalPath != "/login.aspx")
                {
                    if (!view_M06PersonsCategoriesService.HasAccess(HttpContext.Current.User.Identity.Name, catId))
                    {
                        Response.Redirect(string.Format("~/login.aspx?ReturnUrl={0}&qs={1}&CatId={2}{3}",
                                                         Server.UrlEncode(Request.Url.LocalPath),
                                                         Server.UrlEncode(Request.Url.Query),
                                                         Request.QueryString["CatId"],
                                                         Request.QueryString["ArtId"].IsEmpty() ? String.Empty : "&ArtId=" + Request.QueryString["ArtId"]));
                    }
                }
            }

            if (!Page.IsPostBack)
            {
                litAdmin.Text = ConfigurationManager.AppSettings["WebName"].ToString();
                string url = Request.ServerVariables["URL"].ToString();
                if (url.ToLower().StartsWith("/default.aspx"))
                    GetPhotoalbum();
            }
        }
      }
    }

Error message - the line 42 in the app is this one -- Repeater1.DataSource = catList; --

`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: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[NullReferenceException: Object reference not set to an instance of an object.]
   No.Itl.Web.WebApplication.usercontrols.MenuMain2.BindData() in e:\WorkFolder\usercontrols\MenuMain2.ascx.cs:42
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +24
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +41
   System.Web.UI.Control.OnLoad(EventArgs e) +131
   System.Web.UI.Control.LoadRecursive() +65
   System.Web.UI.Control.LoadRecursive() +190
   System.Web.UI.Control.LoadRecursive() +190
   System.Web.UI.Control.LoadRecursive() +190
   System.Web.UI.Control.LoadRecursive() +190
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2427
Darkmage
  • 1,583
  • 9
  • 24
  • 42

1 Answers1

1

Try this:

MenuMain2 mn = (MenuMain2)LoadControl(@"../usercontrols/MenuMain2.ascx");

....

if (name != null)
{
    if (name.Equals("Jhon"))
    {
        mn.RootCategoryId = 1;
    }
    if (name.Equals("Bob"))
    {
        mn.RootCategoryId = 2;
    }
    if (name.Equals("Tom"))
    {
        mn.RootCategoryId = 3;
    }
}

You are loading the UserControl into cont but defining a type of MainMenu2 in mn and adding that object which hasn't been loaded.

andleer
  • 22,388
  • 8
  • 62
  • 82
  • i have already tried that, and that line should have been commented out, i did reference it top of my post that was trying that. this will work `cont.GetType().GetProperty("RootCategoryId").SetValue(cont,49,null);` `cont.GetType().GetProperty("ImageWidth").SetValue(cont,240,null);` `cont.GetType().GetProperty("ImageHeight").SetValue(cont,37,null);` but is this clean and the only way to do it? – Darkmage Jan 17 '13 at 00:02
  • Sorry but I can't follow code that you have commented out that still exists in your question as uncommented... Using reflection on a UserControl type is not the way to go. Fundamentally you are instantiating a type of `MainMenu2` but not loading it using `LoadControl()` and at the same time loading a control into `cont` but doing nothing with that. There seems to be a disconnect there. – andleer Jan 17 '13 at 00:13
  • I have now commented the line that wasent suppose to be there, sorry about that. – Darkmage Jan 17 '13 at 00:20
  • Ok, I updated my answer to reflect your variable change. You are still instantiating `mn` via `new` but since it is a User Control, you need to use `LoadControl` and cast it to your `MainMenu2` type. The same approach I detailed before. – andleer Jan 17 '13 at 01:22