Showing posts with label panel. Show all posts
Showing posts with label panel. Show all posts

Wednesday, March 28, 2012

Tranfering items between Listboxes in an upadated Panel

hi,

i have a page in which there are 2 listboxes. I have also taken 2 buttons (HTML)... Buttons are used to transfer items between Listboxes...

Its working fine and items are transfered between Listboxes...

when i want to put an updated panel and in the <content template>, i put listboxes its not working.....

any anybody has an idea??

Regards,

Suryansu

Would you show us your source code for the page please?


What do you mean by "not working", can you give a sample and a bit more explanation?

If you are having problems with your UpdatePanel specifically, check out:http://blogs.visoftinc.com/archive/2007/09/23/asp.net-ajax--updatepanel-not-working--common-problems.aspx

-Damien


suppose i select one value from drop downbox...As per the value the LIstbox1 is changed and from listbox1 , i will select some items and add to the listbox2...again suppose i select another item from dropdownbox...as per the value in the dropdownbox, the listbox1 items changed...but i want the items in selected in LISTBOX2 should be retained..next time when i select some items from listbox1 to listbox2 , it should be added to the listbox2......

So i thought to use updated panel and so i put DROPDOWNBOX and LISTBOX in the updated panel...so Items in the LISTBOX2 willnot refreshed again and again...items will be only added......

ProtectedSub Page_Load(ByVal senderAsObject,ByVal eAs System.EventArgs)HandlesMe.Load

ListBox2.EnableViewState =True

IfNot IsPostBackThen

Button2.Attributes.Add("onClick","javascript:testme();")

EndIf

ProtectedSub DropDownList1_SelectedIndexChanged(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles DropDownList1.SelectedIndexChanged

Dim varSelectedDDlistAsString

varSelectedDDlist = DropDownList1.SelectedValue

Dim strQueryAsString ="select attribute_value,attribute_display_name from tblattribute_displayname"

ds = objTest.BindData(strQuery)

ListBox1.Items.Clear()

' ||||| Set the DataValueField to the Primary Key

ListBox1.DataValueField ="attribute_value"

' ||||| Set the DataTextField to the text/data you want to display

ListBox1.DataTextField ="attribute_display_name"

' ||||| Set the DataSource the the OleDBDataReader's result

ListBox1.DataSource = ds

ListBox1.DataBind()

EndSub

<%@.PageLanguage="VB"AutoEventWireup="false"CodeFile="Default8.aspx.vb"Inherits="Default8"EnableEventValidation="false" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml">

<headid="Head1"runat="server">

<title>Untitled Page</title>

<scripttype="text/javascript">

var selecetedfield="";

function testme()

{

//alert('hiiiiii');

//alert('hyyy');

//var thisdate= new date();

//alert(thisdate);

//return true;

//alert("hi")

//alert(document.getElementById('ListBox1').options.length);

//alert(document.getElementById('ListBox2').options.length);

var list = document.getElementById('ListBox2');

for(var i = 0; i < list.options.length; ++i)

{

selecetedfield= selecetedfield +",(" +list.options[i].value +") ";

}

// alert(selecetedfield)

// alert(list.options[i].value);

document.form1.HiddenField1.value = selecetedfield;

selecetedfield="";

//alert(document.form1.HiddenField1.value)

}

function setSize(list1,list2)

{

list1.size = getSize(list1);

list2.size = getSize(list2);

}

function selectNone(list1,list2){

list1.selectedIndex = -1;

list2.selectedIndex = -1;

addIndex = -1;

selIndex = -1;

}

function getSize(list){/* Mozilla ignores whitespace,

IE doesn't - count the elements

in the list */

var len = list.childNodes.length;var nsLen = 0;

//nodeType returns 1 for elements

for(i=0; i<len; i++){if(list.childNodes.item(i).nodeType==1)

nsLen++;

}

if(nsLen<2)return 2;

else

return nsLen;

}

var selectedList;

var availableList;

function createListObjects(){

availableList = document.getElementById("ListBox1");

selectedList = document.getElementById("ListBox2");

//alert(availableList)

//alert(selectedList)

}

function delAttribute(){

//availableList = document.getElementById("ListBox1");

// selectedList = document.getElementById("ListBox2");

var selIndex = selectedList.selectedIndex;

if(selIndex < 0)

return;

availableList.appendChild(selectedList.options.item(selIndex));

// selectNone(selectedList,availableList);

// setSize(availableList,selectedList);

}

function addAttribute(){

//alert('hi');

//availableList = document.getElementById("ListBox1");

// selectedList = document.getElementById("ListBox2");

var addIndex = availableList.selectedIndex;

//alert(addIndex)

if(addIndex < 0)return;

selectedList.appendChild(availableList.options.item(addIndex));

// selectNone(selectedList,availableList);

// setSize(selectedList,availableList);

}

</script>

</head>

<bodyonload="createListObjects()">

<formid="form1"runat="server">

<div>

<asp:AccessDataSourceID="AccessDataSource2"runat="server"DataFile="~/PMO - Accounts.mdb"

SelectCommand="SELECT DISTINCT [attribute_section] FROM [tblattribute_displayname]">

</asp:AccessDataSource>

<asp:HiddenFieldID="HiddenField1"runat="server"/>

<asp:ButtonID="Button1"runat="server"Style="z-index: 103; left: 195px; position: absolute;

top: 91px"Text="Click"Width="33px"/>

<inputid="Button3"style="z-index: 107; left: 542px; position: absolute; top: 82px; width: 56px;"

type="button"value=">>"onclick="addAttribute()"unselectable="on"/>

<inputid="Button4"style="z-index: 108; left: 542px; position: absolute; top: 110px; width: 57px;"

type="button"value="<<"onclick="delAttribute()"/>

<asp:ScriptManagerID="ScriptManager1"runat="server">

</asp:ScriptManager>

<asp:UpdatePanelID="UpdatePanel1"runat="server">

<ContentTemplate>

<br/>

<asp:ButtonID="Button2"runat="server"Style="z-index: 101; left: 189px; position: absolute;

top: 119px"Text="Execute"Width="54px"/>

<asp:GridViewID="GridView1"runat="server"Style="z-index: 109; left: 10px; position: absolute;

top: 180px"Height="1px"Width="1px">

</asp:GridView>

<br/>

<br/>

<br/>

<br/>

</ContentTemplate>

</asp:UpdatePanel>

<asp:DropDownListID="DropDownList1"runat="server"DataSourceID="AccessDataSource2"

DataTextField="attribute_section"DataValueField="attribute_section"Height="82px"

Style="z-index: 105; left: 265px; position: absolute; top: 23px"AutoPostBack="True">

</asp:DropDownList>

<asp:ListBoxID="ListBox1"runat="server"Height="107px"Style="z-index: 100; left: 414px;

position: absolute; top: 55px"Width="121px"></asp:ListBox>

<asp:ListBoxID="ListBox2"runat="server"Style="z-index: 102; left: 606px; position: absolute;

top: 56px"Height="103px"Width="126px"></asp:ListBox>

</div>

</form> </body>

</html>

tree view + no postback + update panel

setup:

master page - content page layout

On my content page I want two update panels, one to contain a tree view dynamically generated from a database and the other to contain dynamically generated data (also pulled from a database) based on what is selected in the tree view. It is my understanding that tree view cannot be in an update panel. What is the best strategy for accomplishing this? I don't want a postback to be performed when an item is selected in the tree view. In other words, I don't want the entire page (form) refreshed just because an item in the tree view is selected.

Thanks in advance for any help.

If your treeview doesn't change the contents after the PageLoad, you may be able to have it in an update panel. We found that it doesn't work well if you add nodes to the treeview when you click a parent node, but if you load the full treeview it may be ok. If you need to dynamically add nodes as you click, you would probably need something like the TreeView that telerik has. We were looking at that one until we decided to do our page differently, and that control is not free, but seems to work nice.

The 2nd update panel would have a grid view in it. From the grid view I would add or edit content. If I added content the tree view would need to be refreshed without a full page postback to display the newly added item.

From the sounds of it, this isn't possible with strictly MS controls at the moment.


I just finished this very thing. The page starts with just a pulldown and then based on that value creates a Treeview dynamically without refreshing the page. Then clicking on a node causes another update panel to refresh with specific information.

Pretty convoluted with half Telerik and half MS. The full Telerik approach (Treeview and Update panel) looks easier, but we are using MS AJAX.

My older version of the Treeview (5.3) does not work with MS update panel, so I need to upgrade. I'm not too happy about it, but it seems to work well.

WISH LIST: A direct JavaScript method to postback to an MS update panel. As it is this seems to be the best approach:

http://forums.asp.net/thread/1541012.aspx


I followed the instructions on that thread and I have my update panel refreshing from javascript code. How do I call a javascript function when a tree node is clicked?

in the Telerik Treeview there is a property called "onBeforeNodeClick" and you can set that to the name of a javaScript function to fire when a node is clicked and before postback.


So, I did

myTreeNode.NavigateUrl ="javascript:postBackHiddenField('hardcodedhiddenfieldcontrol','" + uniqueIdentifierOfTreeNode +"')"function postBackHiddenField(hiddenFieldID, clickedID){alert("works");var hiddenField = $get(hiddenFieldID);__doPostBack(hiddenFieldID,'');}
 
I want to use the uniqueIdentifierOfTreeNode in order to modify the select paramter of a gridview in the update panel I'm refreshing from __doPostBack. I have no idea. Any help is appreciated. Is this the best approach to take even?

I forgot to mention the postback and refresh of the update panel is working as I have a label refreshed with the system time.
Nevermind, it looks like I came up with a reasonable solution that works.

Treeview + Update Panel

Hi!

I'm working on atlas and I'm testing some functionnality. I created a page with a treeview contained in an update panel and another update panel that shoul be updated when one selects a node but it doesn't work. Can someone help me?
Here is th source code:

<%@dotnet.itags.org. Page Language="C#" %>"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"> void dataBound(Object sender, TreeNodeEventArgs e) {// Determine the depth of a node as it is bound to data. // If the depth is 1, show a check box. if (e.Node.Depth == 2) { e.Node.ShowCheckBox = true; } else { e.Node.ShowCheckBox = false; } } protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e) {//If a node is selected, display the text in the right table Message.Text = TreeView1.SelectedNode.Text; }</script><html xmlns="http://www.w3.org/1999/xhtml" >First TreeView with an XML File"server"> "text/css"> div.global { width:100%; margin:0px; border:1px solid #99ccff; line-height:150%; } div.header,div.footer { padding:0.5em; color:white; background-color:#99ccff; clear:left; } div.left {float:left; width:200px; margin:0; padding:1em; } div.right { margin-left:270px; border-left:1px solid #99ccff; padding:1em; } "form1" runat="server"> true ID=ScriptManager runat=server/>

class=global>

class="header">Dynamic Atlas Tree View

class=left> "TreeView1" runat="server" DataSourceID="XDS" OnTreeNodeDataBound="dataBound" ShowCheckBoxes=None OnSelectedNodeChanged="TreeView1_SelectedNodeChanged" ShowLines=true> "Kpf" ValueField="ID" TextField="Name"/> "Activity" ValueField="Value" TextField="Value"/> "XDS" runat="server" DataFile="~/XMLTVDataSource.xml">

class=right> Selected elements



"TreeView1" EventName="SelectedNodeChanged "/>

class=footer>KPF Nord

There is a bug with the TreeView. If you remove ShowLines (or set it to false) it should work. When ShowLines is set to true, the controlsometimes generates invalid xhtml.

For more details, check out this post:
http://forums.asp.net/forums/1196633/ShowPost.aspx


Thanks for your reply. This is the error generated when I debug:
"The EventName must be set to a valid event name on the associated control"
And it occurs because of the triggers tag.
Could someone help me to fix this problem?

TreeView and update panel

I am creating a browser for a large document management system, modelled on the way windows explorer works.

So: ... I have a TreeView providing a view of the folders for which I am populating the child nodes on demand when a node is expanded or clicked. (The original method of populating the whole TreeView was impractical since it took several minutes to return and often timeout!)

At the same time, if a node is clicked, I show a list of the documents in that folder.

I can get this working, but somewhere along the way, the client stops working and the TreeView click event stops firing.

Is this a known issue or do you think I am asking too much of the framework?

I have since abandonded Atlas for this and am currently living with a long blank screen between page refreshes, which I think is totally useless for user experience.

Sorry not an immediate answer, but I would also be interested in anybody else's take on this.

I will trying to build more or less the same thing over the next couple of days (for an online content management system) so I'll get back to you then on it (successful or not!), but no I don't think it's asking too much, it's a perfectly logical use of it!


Coming back to this post.. .

How have you implemented the TreeView - just that it is supposed to implement client call back as part of the control so you shouldn't need to have blank screens and whole page refreshes - possibly a pause before expanding if it's big - but no blank screens?

I've just dropped it into my content management system, and while it's not pure Atlas, it seems to work fine using the client call back? Probably I'm missing something as only just started playing with Atlas.

TreeView efficiency

I have a TreeView in an update panel. The Treeview is populated from an XmlDataSource.

I have another panel (ContentPanel) which is updated by this tree.

So, the only reason I have the TreeView in an update panel is so that the ContentPanel can be updated on a TreeNode click.

This works fine - everytime i click on a node of the TreeView, the ContentPanel is updated as expected.

However, when I checked the HttpHeaders and the Body sent by the cleint and the webserver, I noticed that when I click on a TreeView node, the response to the request contains the HTML for the entire tree again!

Why does the TreeHtml need to updated in this way???

Its incredibly inefficient (89k)!!!!

Am I doing something wrong?

Same problem for me...

However I think we not doing anything wrong.

If we click/select a node, it is actually a postback from the updatepanel, therefore the updatepanel refresh itself (sending the treeview again and again)

You can set

EnableClientScript="true"

for the treeview, but it only helps expanding and collapsing the nodes without a postback in my knowledge.

It would be nice a new ajax enabled treeview in the atlas control toolkit.

treeview expand depth 2 collapse to depth level 0.

I have treeview on update panel and loading folders based on user interaction. It works for depth level 2 but at this point clicking the node shows depth level 0 results. is there something I am missing?

here are few lines of crap...

Thanks for you help.

<asp:TreeViewid="SourceTreeView"runat="server"Width="100%"OnSelectedNodeChanged="SourceTreeView_SelectedNodeChanged"OnTreeNodeExpanded="SourceTreeView_TreeNodeExpanded"ShowCheckBoxes="Leaf"ImageSet="Simple"Height="100%"ExpandDepth="1"MaxDataBindDepth="10"NodeIndent="15">

<ParentNodeStyleFont-Bold="False"></ParentNodeStyle>

<HoverNodeStyleForeColor="#5555DD"Font-Underline="True"></HoverNodeStyle>

<SelectedNodeStyleHorizontalPadding="0px"ForeColor="#5555DD"VerticalPadding="0px"Font-Underline="True"></SelectedNodeStyle>

<NodeStyleNodeSpacing="0px"HorizontalPadding="0px"ForeColor="Black"VerticalPadding="0px"Font-Size="10pt"Font-Names="Tahoma"></NodeStyle>

</asp:TreeView>

I am adding nodes per users request using following code, which is same for depth 0,1 and 2.

newNode.Expanded =false;

newNode.ShowCheckBox =false;

newNode.PopulateOnDemand =true;newNode.SelectAction =TreeNodeSelectAction.Select;

treeNode.ChildNodes.Add(newNode);

sg20000:

is there something I am missing

You are missing, that the treeview is not supported in the updatepanelTongue Tied

Check here:

UpdatePanel Control Overview


Maybe you are right and thanks for your help.

I found at some places forward slash was being used, i fixed that and while trying to make it work, made some other changes to node before adding to tree and seems like it is working. I think some nodes had / (creating some escape sequences) or something else to trigger wrapping of tree.

is that treeview on update panel will behave unpredictablly or there are some other issues?


sg20000:

is that treeview on update panel will behave unpredictablly or there are some other issues?

I'm also using treeview with updatepanel, regardless is it not supported.

Main issue which I found that the tree state (selected node, expanded/collapsed nodes state etc.) stays out sync when a postback occurs. Especially when you use any client side capability (populate on demand, enableclientscript=true).

For example:

- Treeview in up

- User coll/exp nodes (no postback yet)

- User select a node, partial postback, selectednodechanged handled for example.

- User select a different node, same as before, but coll/exp state messed up.

- etc.

Without client script features it's ok in up, but slow (big complicated markup, big viewstate etc.)

Treeview ExpandAll problem in beta 1, 2 with EnableClientScript="true"

I have a treeview problem inside an update panel since the first beta. In the last ctp no problem at all.

I have a treeview in the updatepanel with EnableClientScript="true". I have two button in the same update panel, that calls ExpandAll, and CollapseAll in server side click events. That works as expected: the updatepanel refresh the treeview with all node collapsed/expanded. However after then when I expand one node (that not cause a postback yet), and select a node (which now cause a postback), the nodes collapsed/expanded randomly after the updatepanel refresh.

It seems that the server side ExpandAll/CollapseAll could be out of the sync with the client side node expanding/collapsing.

It seems to me when EnableClientScript="true" for a treeview, the tree maintain the expanded/collapsed node in hidden fields, and that hidden field could be out of the sync after a server side ExpandAll/CollapseAll.

?

I write a small javascript function which collapse or expand all node on the cilent side for the treeview. Even the nodes collapsed state is persisted during postbacks/partial postbacks.

The bug still exist, but I will not use the server side ExpandAll in the future...

(just found by the docs that the treeview is not supported in the updatepanel officially, but many of us using it without main problems)

TreeView in an UpdatePanel workaround?

Hi,

I was wondering if anyone might have come across a posting of a workaround for a treeview in an update panel, from what i've read it was not supported in the latest ajax release due to time constraints placed on the development team?

The latest project i'm woking on places me in the spot where i need to get one going in these circumstances.

Cheers

CaffineFizz

We spent a lot of time trying to get our treeview to work inside an update panel, since it did work before the Beta releases, but I haven't seen any work around to allow you to dynamically change the tree after it is initially loaded, unless you get a 3rd party control.

Strange, I'm using V 1.0, downloaded it a week ago. I have atreeview inside of an update panel that is re-loaded via dropdowns (inanother panel) that trigger it's panel.

It works fine.


Is it adding or removing nodes without errors or a full postback?

Yes, if by "adding and removing nodes" you mean calling it's TreeNodePopulate event and adding child nodes on an expand.

Here's how I have it set up

UpdatePanel Filters

UpdatePanel Tree

InPage_Init a call is made to load X number of "filters" dynamically(indicated by records in a database) in the form of dropdownlists. (cascading) The filters are applied to the data that isused by the treeview. The dynamically loaded dropdownseither have a trigger for both updatepanels, or just the treeview panel (depending on if the dropdown is thefinal cascading filter.)

The treeview is then dynamically instantiated and added to it'sown update panel dynamically in Page_Init. The Pre_Renderevent has a toggle to see if the tree has been "Loaded". If not,it loads the tree data, which would use the default selected filters.

Both update panels are set to UpdateMode"Conditional." Upon selecting an item from the dropdown lists thetreeview is re-populated with different filtered data.

Upon"expanding" a node in the treeview the child nodes are added. Full postback? Well, as far as I can tell it isn't. I havetrouble "detecting" that via code, but I do know that the Pre_Renderevent is not fired for the page, which seems to be the only Page eventthat doesn't fire when an "Ajax" callback is made with ASP.Net usingcontrols that are update panel triggers. (or web service calls viaScriptManager for that matter.)

It all works, allcontrols are dynamically loaded. The only "static" items in the.aspx page are the UpdatePanel's themselves (and some other divs andtables and whatnot for formatting).




Are the nodes already there, just not expanded? Are you adding nodes using a form like Node1.Add(ChildNode1)?

mdenn:

Are the nodes already there, just notexpanded? Are you adding nodes using a form likeNode1.Add(ChildNode1)?

No, they aren't allreadythere. My initial loading of the page loads the root node, set'sit's TreeNodePopulate event, and expands just the root. Thisloads the initial Depth 1 nodes (by calling the populate event after Iexpand the root), which if they have children I set theirPopulateOnDemand to true, meaning their children get populate on theserver when the user expands the node (via .Add(node)) for the firsttime. If I set a break point in the event handler it fires on theserver to populate the children.


Just for accuracy, I am using version 1.0.61231.0 of the System.Web.Extensions.dll.

Treeview in modal dialog

I have a modal dialog extender that displays a panel when a button is clicked on the screen. There is a treeview in the panel that has 1...n nodes in it. The panel gets visible just fine, Ok and Cancel buttons work right, but I have a problem with the treeview. When I click on a node in the treeview, modal dialog dissapears from the screen. I've added the treeview to update panel but that didn't work, eighter. Does anyone have had this same problem?

Hello,

I believe treeviews have there own ajax like behaviors and you may be experiencing a postback when the node is clicked.

Can you try to set the property below on your treeview?

EnableClientScript ="False"

Also, is the treeview causing a postback whne you click it? If so, you may need to show the modal dialog extender again after the postback.

Good luck,

Louis

TreeView in UpdatePanel : Heres a working one

Okay, I've seen this mentioned a bunch of times, people can't get TreeView's working in an update panel. Well I've never had a problem. What I figured out was I used a different methodology to fill my tree. Instead of using the "TreeNodeExpanded" event I use the "TreeNodePopulate" event, and set any node that has children's "PopulateOnDemand" property to true. Here's a full solution that uses your file system as an example (since everyone has one) that works for me (running as a file system site at least since I have admin privie's to my drive.)


Either way it demonstrates the concept, and a working solution that uses a TreeView inside of an UpdatePanel. Hopefully this is helpful. If I'm way off base and this isn't REALLY working let me know, but I have a rather complex dynamically loaded treeview solution that works in a production app, and as far as I can tell it is completly populated server side via ajax postbacks.

<%

@dotnet.itags.org.PageLanguage="C#" %>

<%

@dotnet.itags.org.RegisterAssembly="System.Web.Extensions"Namespace="System.Web.UI"TagPrefix="asp" %>

<%

@dotnet.itags.org.ImportNamespace="System.IO" %>

<!

DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<

scriptrunat="server">

protectedvoid Page_Load(object sender,EventArgs e)

{

if (!Page.IsPostBack)

{

BuildTree();

}

}

protectedvoid BuildTree()

{

tvFiles.Nodes.Clear();

TreeNode root =newTreeNode("Drives",@dotnet.itags.org."0");

root.SelectAction =

TreeNodeSelectAction.None;

root.PopulateOnDemand =

true;

root.Selected =

false;

tvFiles.Nodes.Add(root);

tvFiles.ExpandDepth = 1;

root.Expand();

}

protectedvoid tvFiles_TreeNodePopulate(object sender,TreeNodeEventArgs e)

{

TreeNode parentNode = e.Node;if (parentNode.Value ==@dotnet.itags.org."0")

{

PopulateDrives(parentNode);

}

else

{

PopulateNormal(parentNode);

}

}

protectedvoid PopulateDrives(TreeNode node)

{

string[] drives =Environment.GetLogicalDrives();foreach (string drivein drives)

{

TreeNode driveNode =newTreeNode(drive, drive);

driveNode.SelectAction =

TreeNodeSelectAction.None;

driveNode.Selected =

false;

driveNode.PopulateOnDemand =

true;

node.ChildNodes.Add(driveNode);

}

}

protectedvoid PopulateNormal(TreeNode node)

{

string path = node.Value;try

{

DirectoryInfo directory =newDirectoryInfo(path);foreach (FileSystemInfo childin directory.GetFileSystemInfos())

{

TreeNode childNode =newTreeNode();

childNode.Text = child.Name;

childNode.Value = child.FullName;

if (childisDirectoryInfo)

{

if (((DirectoryInfo)child).GetFileSystemInfos().Length > 0)

{

childNode.PopulateOnDemand =

true;

}

}

node.ChildNodes.Add(childNode);

}

}

catch

{

//HACK: ignore erros, probably security, just don't add the nodes

}

}

</

script>

<

htmlxmlns="http://www.w3.org/1999/xhtml">

<

headrunat="server"><title>Untitled Page</title>

</

head>

<

body><formid="form1"runat="server"><div><asp:ScriptManagerrunat="server"id="scriptManager1"></asp:ScriptManager><asp:UpdatePanelrunat="server"id="treePanel"><ContentTemplate><asp:TreeViewID="tvFiles"runat="server"OnTreeNodePopulate="tvFiles_TreeNodePopulate"></asp:TreeView></ContentTemplate></asp:UpdatePanel>

</div></form>

</

body>

</

html>Nice one.

This is excellent, I was close to dropping the TreeView and rolling my own.

However I now have the problem of persisting the TreeView state accross postbacks. The nodes are being populated from a database through the NodePopulated event. Previously we had a function in NodeExpanded and NodeCollapsed that saved the state to a session variable. Any ideas on the best way to do this now?


On closer inspection this doesn't work as expected. It doesn't appear to make use of the UpdatePanel at all, its just using its PopulateOnDemand feature that was always there. When I have another UpdatePanel on the page and cause a postback inside that, the next attempt to expand a node throws back an error:

Invalid postback or callback argument. Event validation is enabledusing <pages enableEventValidation="true"/> in configuration or<%@. Page EnableEventValidation="true" %> in a page. For securitypurposes, this feature verifies that arguments to postback or callbackevents originate from the server control that originally rendered them.If the data is valid and expected, use theClientScriptManager.RegisterForEventValidation method in order toregister the postback or callback data for validation.

Heres the changed code:

<%@. Page Language="C#" %><%@. Register Assembly="System.Web.Extensions" Namespace="System.Web.UI" TagPrefix="asp" %><%@. Import Namespace="System.IO" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BuildTree(); } } protected void BuildTree() { tvFiles.Nodes.Clear(); TreeNode root = new TreeNode("Drives", @."0"); root.SelectAction = TreeNodeSelectAction.None; root.PopulateOnDemand = true; root.Selected = false; tvFiles.Nodes.Add(root); tvFiles.ExpandDepth = 1; root.Expand(); } protected void tvFiles_TreeNodePopulate(object sender, TreeNodeEventArgs e) { TreeNode parentNode = e.Node; if (parentNode.Value == @."0") { PopulateDrives(parentNode); } else { PopulateNormal(parentNode); } } protected void PopulateDrives(TreeNode node) { string[] drives = Environment.GetLogicalDrives(); foreach (string drive in drives) { TreeNode driveNode = new TreeNode(drive, drive); driveNode.SelectAction = TreeNodeSelectAction.None; driveNode.Selected = false; driveNode.PopulateOnDemand = true; node.ChildNodes.Add(driveNode); } } protected void PopulateNormal(TreeNode node) { string path = node.Value; try { DirectoryInfo directory = new DirectoryInfo(path); foreach (FileSystemInfo child in directory.GetFileSystemInfos()) { TreeNode childNode = new TreeNode(); childNode.Text = child.Name; childNode.Value = child.FullName; if (child is DirectoryInfo) { if (((DirectoryInfo)child).GetFileSystemInfos().Length > 0) { childNode.PopulateOnDemand = true; } } node.ChildNodes.Add(childNode); } } catch { //HACK: ignore erros, probably security, just don't add the nodes } }</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"><title>Untitled Page</title></head><body><form id="form1" runat="server"><div><asp:ScriptManager runat="server" id="scriptManager1"></asp:ScriptManager><asp:UpdateProgress ID="prog" runat="server"> <ProgressTemplate>Working...</ProgressTemplate></asp:UpdateProgress><asp:UpdatePanel runat="server" id="treePanel" UpdateMode="conditional"><ContentTemplate><asp:TreeView ID="tvFiles" runat="server" OnTreeNodePopulate="tvFiles_TreeNodePopulate"></asp:TreeView><input type="submit" id="btn1" runat="server" value="same panel" /></ContentTemplate></asp:UpdatePanel> <asp:UpdatePanel ID="upd1" runat="server" UpdateMode="conditional"> <ContentTemplate> <input type="submit" id="btn2" runat="server" value="other panel" /> </ContentTemplate> </asp:UpdatePanel> </div></form></body></html>

Thanks badgrs. My current project has the treeview alwaysbeing re-initialized on any updatepanel postback. That is quiteunfortunate. I will need to evaluate wether to use theUpdatePanel now. I may end up doing a part UpdatePanel part"manual" solution where the items that are selected in the TreeView donot use UpdatePanel tech, but custom web service call-backs.

Thanks for the input.

treeview in update panel does not show styles such as background color,fore color, etc

i have changed the backcolor of my treeview nodes and selected nodes to different colors

wheni draw the treeview outside a updatepanel it shows the colors,

however if I draw it inside the updatepanel it does not show the colors

any help?

Try to post some of your codes here.I'd like to check this. Try to specify postback for the asp:TreeView.
Here are some sample codes about asp:TreeView for your reference.
<WebPart:webpartmanager id="WebPartManager1" runat="server" Personalization-Enabled="true"></WebPart:webpartmanager>
<WebPart:webpartzone id="WebPartZone1" runat="server" bordercolor="#CCCCCC" font-names="Verdana"
padding="6" width="169px">
<PartChromeStyle BackColor="#F7F6F3" ForeColor="White" BorderColor="#E2DED6" Font-Names="Verdana"></PartChromeStyle>
<MenuLabelHoverStyle ForeColor="#E2DED6"></MenuLabelHoverStyle>
<EmptyZoneTextStyle Font-Size="0.8em"></EmptyZoneTextStyle>
<MenuLabelStyle ForeColor="White"></MenuLabelStyle>
<MenuVerbHoverStyle BackColor="#F7F6F3" BorderStyle="Solid" ForeColor="#333333" BorderWidth="1px" BorderColor="#CCCCCC"></MenuVerbHoverStyle>
<HeaderStyle ForeColor="#CCCCCC" HorizontalAlign="Center" Font-Size="0.7em"></HeaderStyle>
<MenuVerbStyle BorderStyle="Solid" ForeColor="White" BorderWidth="1px" BorderColor="#5D7B9D"></MenuVerbStyle>
<PartStyle ForeColor="#333333" Font-Size="0.8em"></PartStyle>
<TitleBarVerbStyle ForeColor="White" Font-Size="0.6em" Font-Underline="False"></TitleBarVerbStyle>
<MenuPopupStyle BackColor="#5D7B9D" BorderWidth="1px" BorderColor="#CCCCCC" Font-Size="0.6em" Font-Names="Verdana"></MenuPopupStyle>
<PartTitleStyle BackColor="#5D7B9D" ForeColor="White" Font-Size="0.8em" Font-Bold="True"></PartTitleStyle>
<ZoneTemplate>
<asp:TextBox ID="tbWebPart" runat="server" Height="19px" Width="197px"></asp:TextBox>
<asp:UpdatePanel ID="upTree" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DataSourceID="SqlDataSource1" AllowPaging="True" CellPadding="4" ForeColor="Black" GridLines="Vertical" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px">
<Fields>
<asp:TemplateField>
<ItemTemplate>
<asp:TreeView ID="TreeView1" runat="server">
<Nodes>
<asp:TreeNode Text="File" Value="File">
<asp:TreeNode Text="New" Value="New"></asp:TreeNode>
<asp:TreeNode Text="Open" Value="Open"></asp:TreeNode>
<asp:TreeNode Text="Exit" Value="Exit"></asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="Edit" Value="Edit"></asp:TreeNode>
<asp:TreeNode Text="WebSite" Value="WebSite"></asp:TreeNode>
<asp:TreeNode Text="Build" Value="Build"></asp:TreeNode>
<asp:TreeNode Text="Debug" Value="Debug"></asp:TreeNode>
<asp:TreeNode Text="Format" Value="Format"></asp:TreeNode>
<asp:TreeNode Text="Help" Value="Help"></asp:TreeNode>
</Nodes>
</asp:TreeView>
</ItemTemplate>
<EditItemTemplate>
<asp:TreeView ID="TreeView2" runat="server" ShowCheckBoxes="All">
<Nodes>
<asp:TreeNode Text="File" Value="File">
<asp:TreeNode Text="New" Value="New"></asp:TreeNode>
<asp:TreeNode Text="Open" Value="Open"></asp:TreeNode>
<asp:TreeNode Text="Exit" Value="Exit"></asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="Edit" Value="Edit"></asp:TreeNode>
<asp:TreeNode Text="WebSite" Value="WebSite"></asp:TreeNode>
<asp:TreeNode Text="Build" Value="Build"></asp:TreeNode>
<asp:TreeNode Text="Debug" Value="Debug"></asp:TreeNode>
<asp:TreeNode Text="Format" Value="Format"></asp:TreeNode>
<asp:TreeNode Text="Help" Value="Help"></asp:TreeNode>
</Nodes>
</asp:TreeView>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
<asp:CommandField ShowEditButton="True" />
</Fields>
<FooterStyle BackColor="#CCCC99" />
<EditRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F7DE" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ProductConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice] FROM [Product]" DeleteCommand="DELETE FROM [Product] WHERE [ProductID] = @.ProductID" InsertCommand="INSERT INTO [Product] ([ProductName], [UnitPrice]) VALUES (@.ProductName, @.UnitPrice)" UpdateCommand="UPDATE [Product] SET [ProductName] = @.ProductName, [UnitPrice] = @.UnitPrice WHERE [ProductID] = @.ProductID">
<DeleteParameters>
<asp:Parameter Name="ProductID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="ProductName" Type="String" />
<asp:Parameter Name="UnitPrice" Type="Double" />
<asp:Parameter Name="ProductID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="ProductName" Type="String" />
<asp:Parameter Name="UnitPrice" Type="Double" />
</InsertParameters>
</asp:SqlDataSource>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="DetailsView1" />
</Triggers>
</asp:UpdatePanel>
</ZoneTemplate>
</WebPart:webpartzone>
</div
Wish the above can help you.

Monday, March 26, 2012

Treeview inside update panel adds nodes when expanded/collapsed

Hi all,

I have something weird going on with a page with 3 treeview controls. I have them set to be expanded by default, but when I click on the collapse (or expand) image on any of the 3 treeviews, a new node is added in my second treeview with repeating data, ie:

TreeView1

1.01.11.22.02.1

TreeView2

3.03.13.2

Now, if I click on 2.0 to collapse it, a new node in TreeView2 will appear, same as 3.0. If I expand 2.0 again, or collapse another node, 3.0 is added again to TreeView2. I'm getting the data from a database table.

Here is the page behind:

protected void Page_Load(object sender, EventArgs e) {if (!Page.IsPostBack) PopulateRootLevel(); PopulateRootLevel_OD(); PopulateRootLevel_RO(); }//TreeView 1//private void PopulateRootLevel() { SqlConnection objConn =new SqlConnection("Data Source=##;Initial Catalog=##;Integrated Security=True"); SqlCommand objCommand =new SqlCommand("select *,(select count(*) FROM ccForum_Posts WHERE parentid=sc.id) childnodecount FROM ccForum_Posts sc where parentID='0' AND status='ac' AND sticky='1' ORDER BY DateTime", objConn); SqlDataAdapter da =new SqlDataAdapter(objCommand); DataTable dt =new DataTable(); da.Fill(dt); PopulateNodes(dt, TreeView1.Nodes); }private void PopulateSubLevel(int parentid, TreeNode parentNode) { SqlConnection objConn =new SqlConnection("Data Source=##;Initial Catalog=##;Integrated Security=True"); SqlCommand objCommand =new SqlCommand("select *,(select count(*) FROM ccForum_Posts WHERE parentid=sc.id) childnodecount FROM ccForum_Posts sc where parentID=@dotnet.itags.org.parentID AND status='ac' ORDER BY sticky, DateTime", objConn); objCommand.Parameters.Add("@dotnet.itags.org.parentID", SqlDbType.Int).Value = parentid; SqlDataAdapter da =new SqlDataAdapter(objCommand); DataTable dt =new DataTable(); da.Fill(dt); PopulateNodes(dt, parentNode.ChildNodes); }protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e) { PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node); }private void PopulateNodes(DataTable dt, TreeNodeCollection nodes) {foreach (DataRow drin dt.Rows) { TreeNode tn =new TreeNode(); tn.ToolTip = dr["Message"].ToString(); tn.Text = dr["subject"].ToString() +" - <span style=font-size:xx-small;> by " + dr["Author"].ToString() +" on " + dr["DateTime"].ToString() +"</span>"; tn.Value = dr["id"].ToString(); tn.NavigateUrl ="~/Post.aspx?MID=" + dr["id"].ToString() +"&PID=" + dr["PostID"].ToString(); nodes.Add(tn);//If node has child nodes, then enable on-demand populating tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0); } }protected void Button_Command(Object sender, CommandEventArgs e) {switch (e.CommandName) {case"Expand": TreeView1.ExpandAll();break;case"Collapse": TreeView1.CollapseAll();break;default:// Do nothing.break; } }//TreeView 2//private void PopulateRootLevel_OD() { SqlConnection objConn_OD =new SqlConnection("Data Source=##;Initial Catalog=##;Integrated Security=True"); SqlCommand objCommand_OD =new SqlCommand("select *,(select count(*) FROM ccForum_Posts WHERE parentid=sc.id) childnodecount FROM ccForum_Posts sc where parentID='0' AND status='ac' AND sticky='2' ORDER BY DateTime", objConn_OD); SqlDataAdapter da_OD =new SqlDataAdapter(objCommand_OD); DataTable dt_OD =new DataTable(); da_OD.Fill(dt_OD); PopulateNodes_OD(dt_OD, TreeView2.Nodes); }private void PopulateSubLevel_OD(int parentid, TreeNode parentNode) { SqlConnection objConn =new SqlConnection("Data Source=##;Initial Catalog=##;Integrated Security=True"); SqlCommand objCommand =new SqlCommand("select *,(select count(*) FROM ccForum_Posts WHERE parentid=sc.id) childnodecount FROM ccForum_Posts sc where parentID=@dotnet.itags.org.parentID AND status='ac' ORDER BY sticky, DateTime", objConn); objCommand.Parameters.Add("@dotnet.itags.org.parentID", SqlDbType.Int).Value = parentid; SqlDataAdapter da =new SqlDataAdapter(objCommand); DataTable dt =new DataTable(); da.Fill(dt); PopulateNodes_OD(dt, parentNode.ChildNodes); }protected void TreeView2_TreeNodePopulate(object sender, TreeNodeEventArgs e) { PopulateSubLevel_OD(Int32.Parse(e.Node.Value), e.Node); }private void PopulateNodes_OD(DataTable dt, TreeNodeCollection nodes) {foreach (DataRow drin dt.Rows) { TreeNode tn =new TreeNode(); tn.ToolTip = dr["Message"].ToString(); tn.Text = dr["subject"].ToString() +" - <span style=font-size:xx-small;> by " + dr["Author"].ToString() +" on " + dr["DateTime"].ToString() +"</span>"; tn.Value = dr["id"].ToString(); tn.NavigateUrl ="~/Post.aspx?MID=" + dr["id"].ToString() +"&PID=" + dr["PostID"].ToString(); nodes.Add(tn);//If node has child nodes, then enable on-demand populating tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0); } }protected void Button_Command_OD(Object sender, CommandEventArgs e) {switch (e.CommandName) {case"Expand": TreeView2.ExpandAll();break;case"Collapse": TreeView2.CollapseAll();break;default:// Do nothing.break; } }//TreeView 3//private void PopulateRootLevel_RO() { SqlConnection objConn =new SqlConnection("Data Source=##;Initial Catalog=##;Integrated Security=True"); SqlCommand objCommand =new SqlCommand("select *,(select count(*) FROM ccForum_Posts WHERE parentid=sc.id) childnodecount FROM ccForum_Posts sc where parentID='0' AND status='ro' ORDER BY sticky, DateTime", objConn); SqlDataAdapter da =new SqlDataAdapter(objCommand); DataTable dt =new DataTable(); da.Fill(dt); PopulateNodes_RO(dt, TreeView3.Nodes); }private void PopulateSubLevel_RO(int parentid, TreeNode parentNode) { SqlConnection objConn =new SqlConnection("Data Source=##;Initial Catalog=##;Integrated Security=True"); SqlCommand objCommand =new SqlCommand("select *,(select count(*) FROM ccForum_Posts WHERE parentid=sc.id) childnodecount FROM ccForum_Posts sc where parentID=@dotnet.itags.org.parentID ORDER BY DateTime", objConn); objCommand.Parameters.Add("@dotnet.itags.org.parentID", SqlDbType.Int).Value = parentid; SqlDataAdapter da =new SqlDataAdapter(objCommand); DataTable dt =new DataTable(); da.Fill(dt); PopulateNodes_RO(dt, parentNode.ChildNodes); }protected void TreeView3_TreeNodePopulate(object sender, TreeNodeEventArgs e) { PopulateSubLevel_RO(Int32.Parse(e.Node.Value), e.Node); }private void PopulateNodes_RO(DataTable dt, TreeNodeCollection nodes) {foreach (DataRow drin dt.Rows) { TreeNode tn =new TreeNode(); tn.ToolTip = dr["Message"].ToString(); tn.Text = dr["subject"].ToString() +" - <span style=font-size:xx-small;> by " + dr["Author"].ToString() +" on " + dr["DateTime"].ToString() +"</span>"; tn.Value = dr["id"].ToString(); tn.NavigateUrl ="~/Post.aspx?MID=" + dr["id"].ToString() +"&PID=" + dr["PostID"].ToString(); nodes.Add(tn);//If node has child nodes, then enable on-demand populating tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0); } }protected void Button_Command_RO(Object sender, CommandEventArgs e) {switch (e.CommandName) {case"Expand": TreeView3.ExpandAll();break;case"Collapse": TreeView3.CollapseAll();break;default:// Do nothing.break; } }

And here is the control:

<%@dotnet.itags.org. Control Language="C#" AutoEventWireup="true" CodeFile="ct_forum_2.ascx.cs" Inherits="ccforum_ct_forum" %><asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <h3>TreeView1 - <asp:ImageButton ID="ExpandButton" runat="server" ImageUrl="~/images/expandall.jpg" CommandName="Expand" OnCommand="Button_Command" AlternateText="Open All Conversations" />   <asp:ImageButton ID="CollapseButton" runat="server" ImageUrl="~/images/collapseall.jpg" CommandName="Collapse" OnCommand="Button_Command" AlternateText="Close All Conversations" /></h3> <asp:TreeView ID="TreeView1" ExpandDepth="10" runat="server" OnTreeNodePopulate="TreeView1_TreeNodePopulate" ImageSet="Inbox" EnableClientScript="False" Width="100%" BackColor="White" BorderColor="#404040" LineImagesFolder="~/TreeLineImages" ShowLines="True" > <ParentNodeStyle Font-Bold="False" /> <HoverNodeStyle Font-Underline="True" /> <SelectedNodeStyle Font-Underline="True" HorizontalPadding="0px" VerticalPadding="0px" BackColor="#404040" /> <NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" /> </asp:TreeView><br /> <h3>TreeView2 - <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/expandall.jpg" CommandName="Expand" OnCommand="Button_Command_OD" AlternateText="Open All Conversations" />   <asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/images/collapseall.jpg" CommandName="Collapse" OnCommand="Button_Command_OD" AlternateText="Close All Conversations" /></h3> <asp:TreeView ID="TreeView2" ExpandDepth="10" runat="server" OnTreeNodePopulate="TreeView2_TreeNodePopulate" ImageSet="Inbox" EnableClientScript="False" Width="100%" BackColor="White" BorderColor="#404040" LineImagesFolder="~/TreeLineImages" ShowLines="True" > <ParentNodeStyle Font-Bold="False" /> <HoverNodeStyle Font-Underline="True" /> <SelectedNodeStyle Font-Underline="True" HorizontalPadding="0px" VerticalPadding="0px" BackColor="#404040" /> <NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" /> </asp:TreeView> <br /> <h3>TreeView3 - <asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="~/images/expandall.jpg" CommandName="Expand" OnCommand="Button_Command_RO" AlternateText="Open All Conversations" />   <asp:ImageButton ID="ImageButton4" runat="server" ImageUrl="~/images/collapseall.jpg" CommandName="Collapse" OnCommand="Button_Command_RO" AlternateText="Close All Conversations" /></h3> <asp:TreeView ID="TreeView3" ExpandDepth="10" runat="server" OnTreeNodePopulate="TreeView3_TreeNodePopulate" ImageSet="Inbox" EnableClientScript="False" Width="100%" BackColor="White" BorderColor="#404040" LineImagesFolder="~/TreeLineImages" ShowLines="True" > <ParentNodeStyle Font-Bold="False" /> <HoverNodeStyle Font-Underline="True" /> <SelectedNodeStyle Font-Underline="True" HorizontalPadding="0px" VerticalPadding="0px" BackColor="#404040" /> <NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" /> </asp:TreeView> </ContentTemplate></asp:UpdatePanel>

Any help will be truly appreciated.

Jose

Well, I hate to answer my own posts, but I guess stepping out of the office gave me a fresh set of eyes. My problem lied in the IsPostBack property:

protected void Page_Load(object sender, EventArgs e) {if (!Page.IsPostBack) PopulateRootLevel(); PopulateRootLevel_OD(); PopulateRootLevel_RO(); }

It should be:

if (!Page.IsPostBack) { PopulateRootLevel(); PopulateRootLevel_OD(); PopulateRootLevel_RO(); }
Hope it helps someone.

Treeview inside update panel

I've got a treeview on my page and I tried to make it works inside an update panel.

For some reasons after the selected event and inserted the value in my db, I'm not able to expend the treeview anymore

Any Idea

PS: Everything is working fine if I remove the UpdatePanel


Thanks for your help

Franck

The TreeView isn't currently supported in an UpdatePanel.

Treeview Malfunction In Update panel

If I put a treeview in an update pannel and put any code in its expand /collapse methods the treeview closes the previous node that you expand. This is fine but when I expand a node and try to collapse that same node it does not collapse but rather stay expanded. Therefore I gathered it does the opposite action to the previously clicked node.

Why does this happen in the update panel, it doesn't happen without it?

The treeview control is not supported officially in the updatepanel!

One problem is that (I think) the treeview use hidden fields to maintain the expanded state of the nodes, and that hidden field stay out of the sync (especially when you use EnableClientScript="true" also). There are tons of other treeview features which not works correctly in the updatepanel.

TreeView PopulateOnDemand within AccordionPane

I have an accordion inside of an Accordion Panel, which is generated from a database. I have the treeview set to populate on demand if there are any subnodes, using the TreeNodePopulate event of the TreeView. Since the Tree is inside of the Accordion Pane, I lose design support, and have to explicitly find and cast the control from the Accordion object. Becuase of this, I lose the event handling binding to that Treeview node. I'm not sure If explicitly fetching and casting is right to begin with, so I'd rather not waste a lot of time trying to manually wire the events to the casted TreeView in codebehind if there is a better way.

Expand Category 1

The target 'ctl00$ContentPlaceHolder2$ctl01$TreeView1' for the callback could not be found or did not implement ICallbackEventHandler.

<atlastoolkit:AccordionPane ID="AccordionPane2" runat="server">
<Header>
<a href="http://links.10026.com/?link=" onclick="return false;" class="accordionLink">Panel 2</a></Header>
<Content>
<asp:TreeView ID="TreeView1" ExpandDepth="0" PopulateNodesFromClient="true" ShowLines="true"
ShowExpandCollapse="true" runat="server" OnTreeNodePopulate="TreeView1_TreeNodePopulate" />
</Content>
</atlastoolkit:AccordionPane>

TreeView tree1;

protected void Page_Load(object sender, EventArgs e)
{
tree1 = (TreeView)AccordionPane2.ContentContainer.FindControl("TreeView1");

}

protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
PopulateSubLevel(Convert.ToInt32(e.Node.Value), e.Node);
}

private void PopulateSubLevel(int parentid, TreeNode parentNode)
{
SqlConnection objConn = new SqlConnection(@dotnet.itags.org."server=SYSSIMERT01\SQLEXPRESS;Trusted_Connection=true;DATABASE=TreeViewSampleDB");
SqlCommand objCommand = new SqlCommand("select id,title,(select count(*) FROM SampleCategories WHERE parentid=sc.id) childnodecount FROM SampleCategories sc where parentID=@dotnet.itags.org.parentID", objConn);

objCommand.Parameters.Add("@dotnet.itags.org.parentID", SqlDbType.Int).Value = parentid;

SqlDataAdapter da = new SqlDataAdapter(objCommand);
DataTable dt = new DataTable();
da.Fill(dt);
PopulateNodes(dt, parentNode.ChildNodes);
}

Hi j05h,

It sounds like the event isn't being properly wired up whenever you postback. If you're creating controls dynamically (and then also their event handlers), be sure to recreate them on postback. If this doesn't help, perhaps you can provide asmall sample demonstrating the problem that I can run.

Thanks,
Ted

Trigger a panel refresh from javascript/pure html control

Hi,

I have a pure HTML tree control, that is outside of an ajax UpdatePanel. I want to write a JS function that triggers a particular panel to refresh, *as if* I hit a submit button inside of the panel. I don't want to put the HTML tree control inside an Ajax panel, as it will loose it's state (it will return to a completely collapsed state).

Putting a button inside the panel, and then running the JSelement.click() event from my tree control works in IE, but Firefox submits the entire page(the submit event is not captured by the AJAX framework in FF in this case,apparently).

I have looked into the client reference documentation at http://ajax.asp.net/docs/ClientReference/Global/default.aspx, and it seems like there should be a way to trigger a postback/panel refresh, but I have not found a way.

The PageRequestManager does not help, since it only monitors existing page requests. I need to invoke a page request, and run something like

PageRequest.Invoke('MyUpdatePanel');

or

var ajaxpanel = document.getElementById('AjaxPanelClientID');
ajaxpanel.update();

A related suggestion:

It would be nice if the UpdatePanel supported client side triggers, not just server side triggers. Consider the following hypothetical code:

<ajax:UpdatePanel ID="ajxUpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<!-- CONTENT -->
</ContentTemplate>
<Triggers >
<ajax:AsyncPostBackTrigger ClientTriggerFunction="MyCustomTrigger" OnTrigger="MyCustomTrigger_ontrigger" />
</Triggers>
</ajax:UpdatePanel>

Then the system would automatically generate the JS function (with the appropriate .NET ajax framework calls that I don't need to know about), so I can call it anywhere on the page, from multiple HTML controls if needed.

<input type="button" value="MyHTMLButton" onclick="MyCustomTrigger('argstring');">

The system should enable a code-behind event handler where I can put my server side code:

protected void MyCustomTrigger_ontrigger(object sender, AjaxClientTriggerEventArgs e) {
//run some server side .NET code here
switch(e.ClientArgString){
...
}
}


You can trigger an asynchronous post back by invoking the __doPostBack function. Just pass in the ID of the control that's either inside an update panel or is marked as a trigger for one. Here's an example:

<asp:UpdatePanel ID="up" runat="server">
<ContentTemplate>
<asp:Button ID="myButton" runat="server" OnClick="myButton_Click" Text="Click me!" />
<asp:Label ID="myLabel" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<input id="myOtherButton" type="button" value="No, click me!" />
<script type="text/javascript">
function pageLoad() {
$addHandler($get('myOtherButton'), 'click', triggerAsyncPostBack);
}
function triggerAsyncPostBack(e) {
__doPostBack('<%= myButton.UniqueID%>', '');
}
</script>

One thing to watch out for is that the first parameter to __doPostBack needs to be the full ID of the control. If you're using master pages, your control IDs will be longer than they appear. Use the UniqueID property to get the full ID or the event handlers for your control won't run on the server.

Also, if you have event validation turned on (the default), you'll get an exception if you don't pass in a correct event argument as the second parameter to __doPostBack. For button controls, it should be the empty string. For other controls, it might be different, but you'll have to experiment to find out.

Hope this helps.


Thank you Jason,

That is the behaviour I was looking for, and it works in Firefox as well as IE. I knew about the _doPostBack function in general, but I did not know the syntax to call it.

Where is the best place to find documentation and syntax for the built-in ASP.NET and AJAX JS functions and calls? For example, I did not know about $get or $addHandler functions.

(I am familiar with similar functions from the prototype.js library).

Thanks again :-)


Another related discovery that is slightly more elegant (I am probably repeating what some already know...but I think its great :-)

Is is not necessary to use a button to trigger the post back inside the panel. I updated a hidden input field with a value, and then submitted thehidden field iteself with __doPostBack, and it worked great. I needed a hidden field to pass in a unique ID anyway, so the panel would know how to refresh itself.

Inside the UpdatePanel:

<input id="txtGroupID" type="hidden" runat="server" onserverchange="txtGroupID_ServerChange" />

JS code:

txt = $get("<%=this.txtGroupID.ClientID %>");
txt.value = somevalue;
__doPostBack("<%=this.txtMatGroupID.UniqueID %>","");



Douglas Smith:

Where is the best place to find documentation and syntax for the built-in ASP.NET and AJAX JS functions and calls? For example, I did not know about $get or $addHandler functions.

The ASP.NET AJAX documentation does document all of these functions. You'd have to know where to look, though. All of the $-prefixed functions seem to be documented in the Sys.UI namespace here:

http://ajax.asp.net/docs/ClientReference/Sys.UI/default.aspx

Browsing through the source code helps find the undocumented stuff.


That will trigger an asynchronous post back, but no event will be raised on the server with that control as the target. You probably want to execute some code to modify the controls inside the update panel or there'd be little point in triggering the asynchronous post back. That's why I used a button control in the example I gave you. If all you want to do is trigger the asynchronous post back and don't care about raising a specific event on the server, you could use the ID of the update panel control as the event target. To me, that would be stating the intention of what you're trying to do a little clearer.

If you don't want to use a button but do want to raise an event on the server, you can use any control that implements IPostBackEventHandler as the event target. Those controls have a RaisePostBackEvent method that gets invoked when a post back is received with their ID as the event target. For button controls, they raise their Click event in that method. That's where your code gets to do its stuff. You could easily create an "empty" custom control that didn't render anything, but could be used as the event target. (I tried using the page control for this, but there's code that prevents you from registering the page as an asynchronous post back trigger.)

It'd be nice if the UpdatePanel control itself implemented IPostBackEventHandler and raised some sort of custom event on the server that let you do this without having to write much custom code. You could simulate this a bit by putting some code inside one of the event handlers on your page and checking to see if the ScriptManager control's AsyncPostBackSourceElementID is the ID of the UpdatePanel control you used as the event target. If so, execute your custom code.

Hope this helps.

Trigger Collapsible Panel Using Javascript

Hi!

Is there a way to trigger expand / collapse on a collapsible panel using javascript? And yes, it must be triggered using javascript instead of server side.

I looked everywhere, but couldn't find any answer. Please help!!

Check outthispost.

trigger event doesnt fire when target control in show/hide panel

I have the following code with the basic required elements to produce the problem:

1<body>2<form id="form1" runat="server">3<asp:ScriptManager ID="ScriptManager1" runat="server" />4<div>5<asp:UpdatePanel ID="UpdatePanel1" runat="server">6<ContentTemplate>7<ajaxToolkit:PopupControlExtender ID="PopupExtender" runat="server" TargetControlID="lbTest"8Position="Right" PopupControlID="buttonPanel">9</ajaxToolkit:PopupControlExtender>10<asp:ListBox ID="lbTest" runat="server" Width="154px"></asp:ListBox>11</ContentTemplate>12<Triggers>13<asp:AsyncPostBackTrigger ControlID="btnAddItem" EventName="Click" />14</Triggers>15</asp:UpdatePanel>16<br />17<asp:Panel runat="server" ID="buttonPanel">18<asp:Button ID="btnAddItem" runat="server" OnClick="btnAddItem_Click" Text="Button" />19</asp:Panel>20</div>21</form>22</body>

The click event is never fired, though the postback occurs.

Any thoughts? Am I doing something "illegal" with the arrangement here? I have a whole form I want to show only in certain circumstances, the results of which should trigger the event to update the main page. How would I do this with Atlas if the given arrangement doesn't work?

TIA, Jeff.

Jeff,

This problem occurs because the PopupControlBehavior's _onClick method calls e.stopPropagation(). That prevents the WebForms.PageRequestManager._onFormElementClick method from getting called. That prevents the asynch postback information from being created correctly. That prevents the asynch postback from working properly.

I believe Ted added the problematic call a long time ago to improve the UI of the PopupControl. I've just pointed him to this thread for more info...

Trigger for Update Panel with Multiple Content Sections on Master Page

Can I use an UpdatePanel in one Content section on a content page with a trigger in another Content section of the same content page?

I have a master page with multiple ContentPlaceHolders which I am using as the template for various pages with a search section and a results section. The search section is contained in one ContentPlaceHolder and the results is contained in another. The content page search section contains an ASP.NET button control (id="btnSubmit") and the content page results section contains an Atlas UpdatePanel containing a Trigger which I would like to tie to btnSubmit. I have tried declaratively to make btnSubmit the trigger, as well as programmatically. When the page loads, I get a "ControlID of trigger must reference valid control" error either way. I have tried substituting btnSubmit.ClientID.ToString inside the trigger definition and this does not work either.

I have another master page/content page combination where both the trigger and the update panel are in the same ContentPlaceHolder/Content section, and I have no problem getting Atlas to work. I am using the April CTP of Atlas.I made a similiar post... I hope I will get a replyhttp://forums.asp.net/1450493/ShowThread.aspx#1450493 from here

Trigger Hack... make any control a trigger for your update panel.

I ran into a problem where I got the error message"A control with ID 'foo' could not be found for the trigger in UpdatePanel bar'."

Basically, I have an update panel with a FormView in it, and in the FormView's EditItem template, I have another UpdatePanel with a Wizard in it. I want the UpdatePanel with the Wizard to trigger on certain Wizard events (like NextButtonClick, PreviousButtonClick), but when the page loads, I get the common error message above.

The long story is, I could just set ChildrenAsTriggers=True for the panel with the wizard, but the different wizard steps have their own UpdatePanels, and I don't want to redraw the whole wizard because someone clicked a radio button, for example... So I decided to fix the problem.

Basically, I wrote a simple control that has an event (UpdateTrigger). It has a single public function to fire that trigger (FireUpdateTrigger). Simple, huh?

So Now I can drop the control on the page right after the UpdatePanel (same nesting level), to be sure that the UpdatePanel can find it. Then, in my Wizard markup, I just add some properties like OnNextButtonClick="WizardEvent" OnPreviousButtonClick="WizardEvent" etc. In the code behind, the WizardEvent trigger simply calls the helper control's FireUpdateTrigger method, which causes the panel to update... like I said, simple.

Here's the code (pretty complexStick out tongue):

using System.ComponentModel;using System;using System.Web.UI;namespace MMCS.WebControls{ [ToolboxData("<{0}:UpdateTriggerHelper runat=server></{0}:UpdateTriggerHelper>")]public class UpdateTriggerHelper : Control, INamingContainer {private static readonly object EventUpdateTrigger =new object(); [Category("Action")] [Browsable(true)] [Bindable(false)] [DefaultValue(null)] [PersistenceMode(PersistenceMode.Attribute)]public event EventHandler UpdateTrigger { add { Events.AddHandler(EventUpdateTrigger,value); } remove { Events.RemoveHandler(EventUpdateTrigger,value); } }public void FireUpdateTrigger() { EventHandler handler = Events[EventUpdateTrigger]as EventHandler;if (handler !=null) { handler(this, EventArgs.Empty); } } }}

Hi,valenumr

Make sure if the following sample can help you:

<%@. Page Language="C#" %>

<%@. Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<link href="http://links.10026.com/?link=StyleSheet.css" mce_href="StyleSheet.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">
var styleToSelect;
function onOk() {
$get('Paragraph1').className = styleToSelect;
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<p id="Paragraph1">
GetContentFillerTextGetContentFillerTextGetContentFillerTextGetContentFillerText</p>
<br />
<ajaxToolkit:Accordion ID="Accordion1" runat="server" ContentCssClass="grey" FadeTransitions="false"
FramesPerSecond="25" TransitionDuration="250" HeaderCssClass="dimgreen" EnableViewState="true">
<Panes>
<ajaxToolkit:AccordionPane runat="server" ID="PaneOne">
<Header>
AccordionPane0
</Header>
<Content>
<a href="http://links.10026.com/?link=javascript:return false" onclick="javascript: LinkButton1.click()">Click here to change
the paragraph style</a>

</Content>
</ajaxToolkit:AccordionPane>
</Panes>
</ajaxToolkit:Accordion>
<div style="visibility: hidden">
<asp:LinkButton ID="LinkButton1" runat="server" Text="Click here to change the paragraph style" /></div>
<asp:Panel ID="Panel1" runat="server" Style="display: none" CssClass="modalPopup">
<asp:Panel ID="Panel3" runat="server" Style="cursor: move; background-color: #DDDDDD;
border: solid 1px Gray; color: Black">
<div>
<p>
Choose the paragraph style you would like:</p>
</div>
</asp:Panel>
<div>
<p>
<input type="radio" name="Radio" id="RadioA" checked="checked" onclick="styleToSelect = 'sampleStyleA';" />
<label for="RadioA" class="sampleStyleA" style="padding: 3px;">
Sample paragraph text</label>
</p>
<p>
<input type="radio" name="Radio" id="RadioB" onclick="styleToSelect = 'sampleStyleB';" />
<label for="RadioB" class="sampleStyleB" style="padding: 3px;">
Sample paragraph text</label>
</p>
<p>
<input type="radio" name="Radio" id="RadioC" onclick="styleToSelect = 'sampleStyleC';" />
<label for="RadioC" class="sampleStyleC" style="padding: 3px;">
Sample paragraph text</label>
</p>
<p>
<input type="radio" name="Radio" id="RadioD" onclick="styleToSelect = 'sampleStyleD';" />
<label for="RadioD" class="sampleStyleD" style="padding: 3px;">
Sample paragraph text</label>
</p>
<p style="text-align: center;">
<asp:Button ID="OkButton" runat="server" Text="OK" />
<asp:Button ID="CancelButton" runat="server" Text="Cancel" />
</p>
</div>
</asp:Panel>
<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender" runat="server"TargetControlID="LinkButton1"
PopupControlID="Panel1" BackgroundCssClass="modalBackground" OkControlID="OkButton"
OnOkScript="onOk()" CancelControlID="CancelButton" DropShadow="true" PopupDragHandleControlID="Panel3" />
</div>
</form>
</body>
</html>

Now you don't get errors like link button with the following name could not be found. :)

Hope this helps,

Let me know if you need more info.