views:

1218

answers:

3

I am using RenderControl in a string builder to add a dropdownlist in a asp:TreeView. My dropdownlist is set to autopostback and I have an event on the SelectedIndexChanged attached. Unfortunaltly, I see my dropdownlist correctly populated inside my treeview, but changing the selection ain't raising events.

here is my code :

DropDownList ddlTest = new DropDownList();
ddlTest.Items.Add("test");
ddlTest.Items.Add("test2");
ddlTest.AutoPostBack = true;
ddlTest.SelectedIndexChanged += ddlTest_SelectedIndexChanged;

TreeNode node = new TreeNode();

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter writer = new HtmlTextWriter(sw);

ddlTest.RenderControl(writer);

node.Text = sb.ToString();
node.ShowCheckBox = false;

There is no method to RegisterEvent on the dropdownlist or something like. Is there any way to achieve what I'm trying to do?

A: 

Check out this thread.

http://social.msdn.microsoft.com/forums/en-US/winforms/thread/de118358-be54-4593-aaaf-d50feb177192/

theG
That is a good thread. However, his problem is that the TreeNode does not have the Controls collection. Hence, the attempt to render control directly.
Ruslan
+1  A: 

Render/RenderControl usually is to late for any kind of event hook ups. Try using PreRender instead.

gsnerf
He won't get any hook ups -- the drop down is not being added to any control's collection. It's being simply written as text.
Ruslan
Good point, I ignored that part :D I have however a solution to that problem: depending on the .net version you have you can use the Method GetPostBackEventReference in Page (deprecated) or ClientScriptManager to manually generate a postback call that can be set to the onchange event of the element.
gsnerf
A: 

In order for your drop down to be able to receive events, it must exist as a control inside some control's collection. It also may need a unique ID (that depends on a number of circumstances).

Right now, you write the drop down's rendered html as a text. It may or may not have the doPostBack function. And if it did, there is no way for the framework to handle it as there is no control to handle.

Since the TreeNode does not have a Controls collection, you could try experimenting with adding one hidden drop down, rendering the rest the way you do and fooling the framework this way. However, that's tricky, as you have to deal with validation, visibility, IDs etc.

You could also try to handle the post back event yourself. Assuming you formed the __doPostBack properly, on page load check Request.Form["__EVENTTARGET"] and Request.Form["__EVENTARGUMENT"] and handle accordingly.

You could also try to create your own treeview...

Ruslan