Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Scott Hugh Alexandar Petersen 349 posts 164 karma points
    Nov 30, 2009 @ 14:52
    Scott Hugh Alexandar Petersen
    0

    Usercontrol using codebehind file in app_code

    Hey there,

    I am trying to create a usercontrol with a label in it (this is quite easy).

    However in the Page_Load method I am trying to modify the label but it returns an error

    Object reference not set to an instance of an object.

    I have been trying to reference to it like this:

    Label lbl = (Label)Page.FindControl("lbl");
    lbl.Text = "modify";

    But it does not work, what am I doing wrong?

    Thanks

    Scott

  • Scott Hugh Alexandar Petersen 349 posts 164 karma points
    Nov 30, 2009 @ 15:05
    Scott Hugh Alexandar Petersen
    0

    I found out myself (thanks to Rick Strahl: http://www.west-wind.com/Weblog/posts/5127.aspx):

    (Label)FindControlRecursive(this.Page.Master, "lbl");



     
      /// <summary>
      /// Finds a Control recursively. Note finds the first match and exists
      /// </summary>
      /// <param name="ContainerCtl"></param>
      /// <param name="IdToFind"></param>
      /// <returns></returns>
      public static Control FindControlRecursive(Control Root, string Id)
      {
       if (Root.ID == Id)
        return Root;
       foreach (Control Ctl in Root.Controls)
       {
        Control FoundCtl = FindControlRecursive(Ctl, Id);
        if (FoundCtl != null)
         return FoundCtl;
       }
       return null;
      }
  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies