Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I am having a really frustrating time with this. I have tried starting from scratch with a new project even, and still it happens. Basically, I have a webpart, with a label and a button in it. When I click the button, I want it to write some text to the label (this is a very basic example which when I get it working will obviously be changed to do something useful). Every time I click the button however, I get a NULLREFERENCEEXCEPTION (object reference not set to an instance of an object), which when I debug shows that the label has been set to null, i.e. not initialised. Below is my code. If anyone could help me out with this I would be eternally grateful.

namespace BusinessReports
{
    [Guid("8aba453e-5083-454b-95c3-3a63a2050601")]
    public class TT001 : System.Web.UI.WebControls.WebParts.WebPart
    {    
        protected Label lbl = null;
        protected Button btn = null;

        public TT001()
        {
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            Label lbl = new Label();
            Button btn = new Button();
            btn.Click += new EventHandler(btn_Click);
            btn.Text = "Click";
            this.Controls.Add(lbl);
            this.Controls.Add(btn);
        }

        void btn_Click(object sender, EventArgs e)
        {
            lbl.Text = "clicked";
        }
    }
}

The webpart loads into SharePoint just fine, but throws the error when you click the button.

share|improve this question

1 Answer 1

in your CreateChildControls method you are creating a new Label and Button and assigning them to local variables lbl, and btn, rather than the class level fields lbl, and btn.

This means when you get to the btn_Click method, you've never actually set lbl

try this instead:

protected override void CreateChildControls()
{
    base.CreateChildControls();

    lbl = new Label();
    btn = new Button();
    btn.Click += new EventHandler(btn_Click);
    btn.Text = "Click";
    this.Controls.Add(lbl);
    this.Controls.Add(btn);
}
share|improve this answer
    
That's got it! I feel a bit of a fool for not spotting that, but am so relieved to have it working, I'll get over it! Thank you SO much for saving me from more hours of frustration. –  Vicky Dec 1 '10 at 15:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.