Aceessing controls in a Panel

I dynamically create some controls at runtime and add them into a panel.

Later on, I try to access those controls in a different function, butI get a null object error

Does anybody know what Im doing wrong?
Protected Sub TreeView1_SelectedNodeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TreeView1.SelectedNodeChanged
   Dim TextBox1 As New TextBox
   TextBox1.ID = "a"
   TextBox1.Style("Position") = "Absolute"
end sub
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        Dim txt As TextBox = New TextBox()
        txt = Panel1.FindControl("a")   'crash here
        Label1.Text = txt.Text
end sub

Open in new window

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Instead of setting set = "a".
Also, try accessing panel1 by preceeding with me. So me.panel1.findcontrol("a").

My previous post is incorrect by the way, i confused with another method.
bdb12Author Commented:
ok I cant find an attribute of Name for textboxs....

Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

the problem is dynamic controls are lost on postback, if you dont create them again in page load event. try the same code from btnsubmit_click event in page load event, it will work. you need to add a check to check if it is  a postback case.

check this for a sample

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
bdb12Author Commented:
Ah I didnt know they where lost....that makes sense....I'll try out that code now and get back to you. Thx
bdb12Author Commented:
Still working on this....home time now so will get into it tomorrow....thx
Éric MoreauSenior .Net ConsultantCommented:
bdb12Author Commented:
Thank you
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.