vb response.writefile NullReferenceException: Object reference not set to an instance of an object.

JS List
JS List used Ask the Experts™
I'm using response.writefile("") on an .aspx web page.  
"" contains a table and a bunch of labels like this: <asp:Label ID="label1" runat="server" Text="" />
On page load, after I've retrieved the data, I'm trying to put text in those labels.

Coming up with error:
Object reference not set to an instance of an object.
NullReferenceException: Object reference not set to an instance of an object.

Here the code behind
Dim lbl1 As Label
lbl1 = DirectCast(FindControl("label1"), Label)
lbl1.Text = Row("xNames").ToString

I'm creating several reports that the some of the same pages.  
Each report has a big long SQL string call that pulls data from 7 different tables.  All the reports don't need the same data.

Instead of duplicating coding to create the common pages on the report, I'm trying to include them.  
This way I can pull 1 set of data with 1 call and not several for each report.
I tried creating usercontrols but the same problem happens.

I read someplace where you can't use findcontrol on a label.  Is this true?  Is there an alternative?

Is there a better way to do this?

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®


Thanks Scott
Most Valuable Expert 2011
Top Expert 2015
Controls in ASP.NET WebForms are placed into various containers on your page. The page itself is also a container. If you call the page's FindControl method, then it is expected that the control you seek is directly on the page itself--i.e. not in a nested container. If your control actually resides within a nested container (e.g. Panel, GroupBox, etc.) on the page, then you have to call FindControl on the container itself. Check to make sure that you are calling FindControl against the correct container.
Jaime OlivaresSoftware Architect
Top Expert 2008

You need a recursive FindControl function. Have a look at the answer of this question:
This is what's working.

Pull all the data, from SQL, for the entire report.  (From the main report page)
 Store the data in a table and save it in the Session.
 Create a User Control for each section
 Pull the info from the Session table for the User Control labels

Good thing is there isn't a lot of SQL calls going back and forth.  And I can reuse the Page sections as need without much work.  It generates pretty quick

Bad thing is sometimes it's difficult to get all the data into 1 SQL string.  But practice makes perfect!


Based on Kaufed's answer - I found another solution to the problem.  
Create usercontrols for the individual pages
Create main report that calls all the data once and uses the usercontrol pages as needed.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial