2013-01-16 2 views
3

usercontrol과 관련된 문제가 있습니다. 나는 몇 시간 동안 그 일을 해왔으니 이제 도움을 청해야합니다.값을 사용자 정의 컨트롤에 바인딩하는 중

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

잘 작동 :이 같은 마크 업 페이지에서 사용자 정의 컨트롤을 호출하는 경우

.


나는 또한 그것을 호출 할 수 있습니다

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

하고도 잘 작동합니다. 그렇지만 나는 필요한만큼 속성을 설정하지 않습니다.


그러나 아래 코드의 코드와 같은 자리 표시 자로 호출하면 작동하지 않습니다. 내가 페이지의 맨 아래에 게시 한 오류가 나타납니다.

Usercontrol 코드 파일 - MenuMain.ascx.cs 다음 Masterpage에 대한 코드 숨김

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(); 
    } 
} 

:

 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(); 
      } 
     } 
     } 
    } 

오류 메시지 - Repeater1.DataSource = catList; - -

응용 프로그램에서 선 (42)이 하나
`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 
+0

이 줄'MenuMain2.ascx.cs : 42'를 발견 할 수 있습니까? – Aristos

+0

예, Repeater1.DataSource = catList; – Darkmage

+0

그래서'GetPublishedByParentCategoryId'는 null을 반환합니다 ...? 또는 DataBind에서 오류가 발생하면 컨트롤의 렌더링 내부에 null 점을 찾습니다. – Aristos

답변

1

시험해보기 :

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; 
    } 
} 

당신은 cont에 UserControl을로드하지만 mnMainMenu2의 유형을 정의하고로드되지 않은 객체를 추가.

+0

나는 이미 그걸 시도해 봤고 그 줄이 주석 처리되어 있어야했다. GetContenty ("ImageWidth"). SetValue (cont, 49, null);이 값은 GetContenty ("RootCategoryId" SetValue (cont, 37, null); ' 'Cont.GetType(). GetProperty ("ImageHeight"). – Darkmage

+0

미안하지만 미안하지만 당신의 질문에 코멘트가 존재하지 않는다고 주석 처리 한 코드를 따라갈 수 없습니다 ... UserControl 유형에 리플렉션을 사용하는 것은 방법이 아닙니다. 근본적으로 당신은'MainMenu2' 타입을 인스턴스화하지만'LoadControl()'을 사용하여로드하지 않고 컨트롤을'cont'에로드하는 동시에 아무것도하지 않습니다. 거기에 연결이 끊어져있는 것처럼 보입니다. – andleer

+0

나는 거기에 있다고 생각했던 줄을 주석으로 남겼다. 미안하다. – Darkmage

관련 문제