Dynamic controls II



I know why the code below does not work, I just need to know if there is a
way around it.

I create a treeview control and add an SelectedChanged event to it. This
happens in the OnInit method. Now, because I need some values from ViewState
before I add nodes, I don't add nodes until the onPreRender method and the
treeview is also added to it origin panel in that method.

However, seems that the event is not firing if I do that. If I put the line
"patest.Controls.Add(tvTeamList);" in the OnInit so the Treeview is added
there, then it works. The nodes and the tree otherwise is rendered ok.

The short version of the code:

protected Button tb = new Button();
protected TreeView tvTeamList = new TreeView();

override protected void OnInit(EventArgs e)
tvTeamList.ID = "tvTeamList";
tvTeamList.EnableViewState = true;
tvTeamList.SelectedNodeChanged += new

// This is the panel on the aspx site where rendering the treeview

protected override void OnPreRender(EventArgs e)

if (ViewState["filter"] == null)
TreeNode tn = new TreeNode();
tn.Text = "NodeText";
tn.Value = "NodeValue";

protected void tvTeamList_SelectedNodeChanged(object sender, EventArgs e)
string dg = "Dont get to this point";

As I said, moving the statement where the treeview is added to the panel
control into the OnInit, works.

So the question is, is there anyway I can wait to add the treeview until I
get to the OnPreRender level? Tried to use the FindControl of the parent
control, but result is the same. I assume the event is not wired if i bind
the control that late in the flow, but it would be nice if I could somehow.




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