Dynamically added controls are lost on a Postback

D

Dejan

Hi,

i created a custom control overriden from HierarchicalDataBoundControl. In
method PerformDataBinding I add some controls (Controls.Add(new TextBox)). It
works fine on a first load, but on a postback there are no controls.
I know I have to create them again, but a method PerformDataBinding doesn't
occour on a PostBack. Can someone tell me where and when I have to create
them?

Thanks in advance,
Dejan
 
J

John Saunders

Dejan said:
Hi,

i created a custom control overriden from HierarchicalDataBoundControl. In
method PerformDataBinding I add some controls (Controls.Add(new TextBox)).
It
works fine on a first load, but on a postback there are no controls.
I know I have to create them again, but a method PerformDataBinding
doesn't
occour on a PostBack. Can someone tell me where and when I have to create
them?

I know how we did this in .NET 1.1. Maybe you can modify the following for
2.0:

1) During databinding, something in the data tells you that you need your
text box. For the sake of discussion, let's assume that the data source has
a "TextBoxNeeded" column. You should put that value into ViewState. This is
typically done by setting the data source column value into a control
property (bool TextBoxNeeded) which sets and gets its value from
ViewState["TextBoxNeeded"].
2) During CreateChildControls, you would check that property to see if you
need to create the textbox. On the initial page request, the property would
be true because you did the data bind and the data source said that the
property should be set. On postback, the property would be set from
ViewState. In either case, you would then create your textbox.

A variation on this theme are that if the textbox takes any of its
properties from the data source, then you'll want to create it during the
data bind and set the properties from the data source. Set a flag indicating
that you've created it so that you don't create it again during
CreateChildControls on the initial request. On the postback, when
CreateChildControls is called, your flag will not have been set, so you
would then create the text box and add it to the Controls collection. At
that time, the text box will set its own properties from its own part of
ViewState.

If you find that some of this applies to 2.0, please post your results here.
I haven't written any 2.0 controls yet, and would be interested in the 2.0
way of doing this.

John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top