Showing posts with label event. Show all posts
Showing posts with label event. Show all posts

Wednesday, March 28, 2012

Tree view nested in Accordion taking two clicks to fire selectedNodeChanged event

I have a treeview in one of my accordion panes. When I click on a node for the first time, instead of firing the selectedNodeChanged event, it just goes through a normal postback. However the second time I click it, the event is fired correctly. Is there another event being fired that I'm not seeing?

Here's a trimed down version of the code. Thanks for any ideas. -d

<atlasToolKit:Accordion ID="navAccordion" runat="server" Height="410"
FadeTransitions="true" FramesPerSecond="40"
TransitionDuration="250"
AutoSize="None"
>

<atlasToolKit:AccordionPane ID="AccordionPane2" runat="server">
<Header><a href="http://links.10026.com/?link=" onclick="return false;" class="accordionLink">Tank Groups</a></Header>
<Content>
<asp:Panel ID="navPanel" runat="server" ScrollBars="auto" CssClass="extraPadding" BackColor="white" Width="180" Height="200">
<asp:TreeView ID="navTankGroups" OnUnload="nav_Unload" OnSelectedNodeChanged="nav_SelectedNodeChanged" runat="server" SkinID="nav" >
<Nodes>
<asp:TreeNode Text="Page 1" Value="~/page1.aspx" />
<asp:TreeNode Text="Page 2" Value="~/page2.aspx" />
</Nodes>
</asp:TreeView>
</asp:Panel>
</Content>
</atlasToolKit:AccordionPane>
</atlasToolKit:Accordion>

Here's the selectedNodeChanged routine.

Protected Sub nav_selecedNodeChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim navTankGroups As TreeView = CType(AccordionPane2.ContentContainer.FindControl("navTankGroups"), TreeView)
If Not navSchedule.SelectedNode.ValuePath = String.Empty Then
Response.Redirect(navTankGroups.SelectedNode.Value)
End If
End Sub


This appears to only be an issue on master pages. I placed the accordion in a new page and it worked fine. Anyone have an idea on why it is taking two clicks in the masterpages? -d

Hi dtamber,

I'm not sure what's going on with this... could you perhaps post the simplest possible version you have that still causes the problem?

Thanks,
Ted


Look at the source code before and after the button click, there is one of 2 possibilities.

1. someting being created dynamicly doesn't have an ID property set, in this case you'll see the treeview control in the source with different names

Like ctl03 and ctl05 in the treeview's name

2. I have fixed my postback issues by adding a hidden field to each accordion pane at page_init. I don't know why this fixes the erradic behavior, but it does.

Let me know if either of these works.

Chris


I think this needs a bump.

I just tried using an accordion in a usercontrol and added 3 panes, each containing an updatepanel containing a button.

The button click event is not fired. Adding a hidden field as Chris suggested allows the click event to fire.

Nathan


I also ran into the exact same problem. I was using a gridview inside an accordion and the events weren't firing the first attempt. If you add a control to it during OnInit then it appears to work. My assumption is that there's a problem with the RenderControls or something.

Astynax777:

I also ran into the exact same problem. I was using a gridview inside an accordion and the events weren't firing the first attempt. If you add a control to it during OnInit then it appears to work. My assumption is that there's a problem with the RenderControls or something.

Astynaxx777 - This clicking twice problem has been a real issue for me. Can you please elaborate with a small example if possible? You mean to add a control to the AccordionPane when the page loads (through the code behind)?

Your help would be greatly appreciated.


I ran into the same problem where I couldn't get a Button click event to fire off until I did whatCConchelos tried:

"2. I have fixed my postback issues by adding a hidden field to each accordion pane at page_init. I don't know why this fixes the erradic behavior, but it does."

Here's a basic example:

 
<body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <div> </div> <cc1:Accordion ID="Accordion1" runat="server"> <Panes> <cc1:AccordionPane ID="AccordionPane1" runat="server"> <Header>Test1</Header> <Content> <asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton> </Content> </cc1:AccordionPane> <cc1:AccordionPane ID="AccordionPane2" runat="server"> <Header>Test2</Header> <Content> <asp:Button ID="Button1" runat="server" Text="Button" /> </Content> </cc1:AccordionPane> </Panes> </cc1:Accordion> </form></body>

The Button1 click event would not get called until I added a hidden field to the AccordionPane that contained Button1 on the Page_Init:

Private Sub Page_Init(ByVal senderAs System.Object,ByVal eAs System.EventArgs)Handles MyBase.InitDim myAccordionPaneAs AccordionPaneDim myTextBoxAs New TextBox myTextBox.Visible =False myAccordionPane =MyBase.FindControl("AccordionPane2") myAccordionPane.Controls.Add(myTextBox)End Sub

I thinkAstynax777 is right - there must be something wrong with the controls inside an AccordionPane when being rendered.


Thank you very much. It should be noted that after Astynax777's suggestion I tried it with a button and I forgot to hide it, and it didn't work as expected.

Excellent example, thanks again.


Hi,

has anyone found out more about this issue? As indicated in a previous post, the issue appears to be that controls are not rendered properly the first time the accordion is loaded. When the postback occurs, the controls have a different id, and no event is fired since it cannot be hooked up to the appropriate control (since the ID has changed).

I have a slightly different problem than those posted above as the accordion I'm working with is loaded via a datasource. I cannot add controls on the init event as a temporary fix. Any idea for a workaround would be greatly appreciated until this is resolved.

Thanks


btw, this "click twice" error disappears when I have only 1 accordion control on a page. If there are two accordion controls (one is data bound, the other is not), then I have to click twice. When I only have the databound accordion, it works as intended.

The good thing is that adding the "invisible" control to each pane in the Accordion which is not databound has fixed the "click twice" error in the databound Accordion.


Ok, I think I have this problem fixed. You can see the changes I made athttp://www.codeplex.com/AtlasControlToolkit/WorkItem/View.aspx?WorkItemId=5796 . There's 2 files I uploaded for that issue. I might help you... or it might not, I have not tested it for your problem but it certainly fixed mine! Good luck.


Has anybody else tried it with the new 10660 release? For me, the event handling never worked. My accordion is completely databound and does not contain any unbound panes. Consequently, the workaround will not work for me. I've just tried it with 10660, but no change.

Dennis Doomen
Aviva Solutions


I was having all of those 'click twice' problems but in randomly places. I used Accordions on many different pages and I couldnt figure out why it worked on some pages and didnt on others. I realized that on the page that it didnt work I was doing my control loading during OnInit and on my other pages that did work it was during PageLoad. Im guessing you have to make sure that everything must be done in one or the other. If you have User Controls make sure that your logic and things are also in it's page load as well. Dont mix and match :)

TreeView + SelectedNodeChanged + UpdatePanel = Problems

I wondered if anyone else has had strange behavior when specifying the SelectedNodeChanged event of a TreeView as an AsyncPostBackTrigger for an UpdatePanel. I'm currently seeing erratic behavior. Some nodes will post back when selected, and others won't; it seems totally random.

There was no problem before I upgraded fromRelease 60914 of the toolkit.

While we work closely with the ASP.NET AJAX team when developing the Toolkit, they're the real experts on general ASP.NET AJAX issues. Your problem doesn't seem to be directly related to the Toolkit, so we'd appreciate if you considered posting to one of theother newsgroups such asAJAX Discussion and Suggestions. Your post will be more helpful to others looking for similar advice if it's in the right place. Thank you!

I have Treeview inside asp:UpdatePanel.{ASP.NET Ajax RC version}

Its not maintaining its viewstate properly while expanding/collepsing nodes.

If I remove Updatepanel,, it works fine.

Is it a bug ?? what could be relevent and reliable solution.

Thanks in advance.

Rahul Jain

KY


This is still the wrong forum for this question, but I'll answer anyway: TreeView is not supported inside an UpdatePanel. Seehttp://ajax.asp.net/docs/overview/UpdatePanelOverview.aspx.

If you have a TreeView inside an UpdatePanel, it is better to have the following properties set as such PopulateNodesFromClient="false" and EnableClientScript="false". Hope this will solve at least some random problems when clicking/expanding/collapsing a treenode.

Cheers,

vince.n3t


Hello,

I tried a few things in my code & everything started working fine. But I get an error on the IE7 page (error: Invalid argument, Line: 43, Character:238).

On putting a break point & then debugging, I get a break on the JS page & the error points to --> accordion.insertBefore(wrapper, content)

I have no idea what this error means & how to debug it. Because everything on the IE7 page works as I want it to, but I get this error on the status bar as: 'Done, but with errors on page'.

Please help me with this error, as this a project I am working on & I need to complete it before the deadline. Any other options for creating a TreeView using any of the Ajax Extenders with the Update Panel are also welcome.

MyDefault.aspx :

<%@. Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AJAXRajeev.Default" %>

<%@. 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">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>
Sales Professional Desktop II
</title>
</head>
<body>
<form id="form1" method="post" runat="server">
<div class="Default" style="float:left">

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true">
<Services>
<asp:ServiceReference Path="WebService.asmx" />
</Services>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div id="MyAccordion" runat="server">
<ajaxToolkit:Accordion ID="Accordion1" runat="server" SelectedIndex="0">
<Panes>
<ajaxToolkit:AccordionPane ID="AccordionPane1" runat="server">
<Header><a href="http://links.10026.com/?link=" onclick="return false;" class="accordionlink" />
External Documents
</Header>
<Content>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Panel ID="navPanel" runat="server" ScrollBars="auto">
<asp:TreeView ID="TreeView1" runat="server" BackColor="Transparent" ExpandDepth="1" MaxDataBindDepth="2" NodeIndent="10" SkipLinkText="skip nav" Target="~/Default.aspx" ToolTip="navigation" Font-Names="Verdana" Font-Size="Smaller" ForeColor="Gray" ShowLines="True" PopulateNodesFromClient="true" EnableClientScript="True">
<ParentNodeStyle Font-Bold="False" ImageUrl="~/Images/folder.gif" />
<HoverNodeStyle Font-Underline="True" />
<SelectedNodeStyle Font-Underline="True" HorizontalPadding="0px" VerticalPadding="0px" ImageUrl="~/Images/folder_open.gif" />
<RootNodeStyle ImageUrl="~/Images/folder.gif" />
<NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" ImageUrl="~/Images/folder_open.gif" />
</asp:TreeView>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
External Documents
</ProgressTemplate>
</asp:UpdateProgress>
</Content>
</ajaxToolkit:AccordionPane>
</Panes>
</ajaxToolkit:Accordion>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress2" runat="server">
<ProgressTemplate>
External Documents
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</form>
</body>
</html>

MyDefault.aspx.cs :

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AllianceBernstein.Wsg.Retail.Common.Data;
using System.Data.SqlClient;
using System.IO;
using System.Drawing;
using System.Web.Services;
using AjaxControlToolkit;

namespace AJAXRajeev
{
[Serializable]
public partial class Default : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label lblSelectedPath;
protected const string ROOT_PATH = "2:";

protected TreeView Tree
{
get
{
return Accordion1.FindControl("TreeView1") as TreeView;
}
}

protected UpdatePanel UpdatePanel
{
get
{
return Accordion1.FindControl("UpdatePanel1") as UpdatePanel;
}
}

protected void Page_Load(object sender, System.EventArgs e)
{
//UpdateProgress1.AssociatedUpdatePanelID = this.UpdatePanel.ClientID;

Ajax.Utility.RegisterTypeForAjax(typeof(AJAXPortal));
if (!Page.IsPostBack)
{
LoadTree();
}

Folder[] aFolders = Folder.List();

this.Tree.ExpandAll();
}

[Ajax.AjaxMethod()]
private void LoadTree()
{
if (this.Tree == null)
{
return;
}

Folder[] aFolders = Folder.List();
foreach (Folder oFolder in aFolders)
{
TreeNode oTreeNode = new TreeNode();
oTreeNode.Text = oFolder.Name;
oTreeNode.ImageUrl = "/images/folder.gif";
this.Tree.Nodes.Add(oTreeNode);

}
}

internal DataSet ListFolder()
{
throw new Exception("The method or operation is not implemented.");
}


}
}

Please help me with this.

Karamchand

Monday, March 26, 2012

Treeview inside updatepanel postingback on selectednodechanged

Hi,

I'm having problem with a treeview inside an updatepanel on my page. The treeview is populated from the client on the treenode pouplate event. The selection of a node in the treeview triggers the content of another updatepanel to be displayed according to the selected node. Everything works fine exept that the whole tree is postedback on the selectednodechanged event even tough the triggers for that update panel is on treenodepopulate.

Here's the code :

<%-- The treeview --%> <atlas:UpdatePanel ID="uptv" runat="server" mode="conditional" 
<ContentTemplate
<asp:Panel ID="panTree" runat="server" Height="600px" ScrollBars="Auto" Style="z-index: 102;
left: 3px; position:absolute; top:5px;" Width="450px" CssClass="bordures"
<asp:TreeView ID="tvEquipement" runat="server" Height="100%" Style="z-index: 100; left: 0px;
position: absolute; top: 0px" Width="100%" ForeColor="ControlText" ExpandDepth="2" NodeIndent="10"
<SelectedNodeStyle BackColor="#D09200" Font-Bold="True" ForeColor="HighlightText" BorderColor="HighlightText" />
<RootNodeStyle Font-Bold="True" /
</asp:TreeView
</asp:Panel
</ContentTemplate
<Triggers
<atlas:ControlEventTrigger ControlID="tvEquipement" EventName="TreeNodePopulate" /
</Triggers
</atlas:UpdatePanel
<atlas:UpdatePanel ID="upInfos" runat="server" mode="conditional"
<ContentTemplate>
<%-- stuff based on the selected node--%> </ContentTemplate
<Triggers
<asp:ControlEventTrigger ControlID="tvEquipement" EventName="SelectedNodeChanged" /
</Triggers
</atlas:UpdatePanel>

Any hep or idea would be greatly appreciated.

Thanks,

Max

The treeview is inside the update panel and childrenAsTriggers is set to true (Default is true). Therefore, if you click on control inside the update panel it would result in the
update panel getting updated. What you have to do is set ChildrenAsTriggers = false for the update panel with treeview.

On a different note: Treeview inside an update panel is not a supported scenario.

vineetc


Thanks for your reply. I don't seem to have that property. Is this a new feature from the Ajax Beta release. I'm still working with the last Atlas release.

The tree wasn't in an updatepanel at first, but I had to put it in one because the selectedvalue property was messed up when outside the updatepanel.

Max


Ajax beta release has this property. Also Property "Mode" of the update panel is renamed to "UpdateMode".

vineetc


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 TreeNodePopulate event.

I have recently installed the AJAX Beta 2 Extensions having used the ATLAS CTP. Having installed it I removed the DLLs from the Bin directory. On two of my pages in the application I am using the Treeview controls which only populate child nodes when each of the parent nodes are clicked on. On one page this the treeview works fine and populates on demand -

1protected void ATreeview_TreeNodePopulate(object sender, TreeNodeEventArgs e)
2 {
3switch (e.Node.Depth)
4 {
5case 0:
6break;
7case 1:
8 PopulateTreeview(e.Node);
9break;
10 }
11 }


The PopulateTreeview method takes the node that should be populated (which for e.g. is the Category) and creates all the product nodes. At the moment the TreenodePopulate event does nothing as I just want to see whether it actually raises the event. When I discovered the problem I took out all the code in this event. The code at the moment is as follows:

1protected void ATreeview_TreeNodePopulate(object sender, TreeNodeEventArgs e)
2 {
3 lblMessage.Text ="inside the treenode populate " + e.Node.Depth.ToString();
4 lblMessage.Visible =true;
5 }

When I debug this and expand a node I get the following error:


"Microsoft JScript runtime error: 'ctl00_ContentPlaceHolder1_tvUsersNoGroup_Data' is undefined" - I have no choice but to press Break and stop the application from running. In the IDE it just highlights this line TreeView_PopulateNode(ctl00_ContentPlaceHolder1_ATreeview_Data,1,ctl00_ContentPlaceHolder1_ATreeviewn1,ctl00_ContentPlaceHolder1_ATreeviewt1,null,'t','A Category','TopNode\\3016','f','','tf')

The design source code is as follows:

<asp:UpdatePanel ID="upUsers" runat="server"> <ContentTemplate> <table border="0" class="report_treeview"> <tr style="background-color:#6178BE; color: #FFFFFF;font-weight:bold; font-size:80%;text-align:center;"> <td>Users not in selected security group</td> <td><asp:DropDownList ID="ddSecurity" runat="server" AppendDataBoundItems="True" AutoPostBack="true" OnSelectedIndexChanged="ddSecurity_SelectedIndexChanged"> <asp:ListItem Selected="True" Text="Please select a security group" Value="0"></asp:ListItem> </asp:DropDownList></td> <td>Users in selected security group</td> </tr> <tr> <td style="vertical-align: top; width: 300px; text-align:left;"> <asp:TreeView id="ATreeview" runat="server" showlines="true" visible="false" OnTreeNodePopulate="tvUsersNoGroup_TreeNodePopulate"></asp:TreeView> </td> <td style="border-right: solid 1px #DDDDDD;border-left: solid 1px #DDDDDD;text-align:center;"> <asp:Button ID="btnAddUser" runat="server" Text=">>" CssClass="option_button" OnClick="btnAddUser_Click" ToolTip="Add selected users." /> <p /> <p /> <asp:Button ID="btnRemoveUser" runat="server" Text="<<" CssClass="option_button" OnClick="btnRemoveUser_Click" ToolTip="Remove selected users." /> </td> <td style="vertical-align: top; width: 300px; text-align:left;"> <asp:Label ID="lblStatus" runat="server"></asp:Label></td> </tr> </table> <p /><asp:Label ID="lblMessage" runat="server" CssClass="labelStatus"></asp:Label> </ContentTemplate> </asp:UpdatePanel>
Anyone else come across this problem? Why is my other page fine and this page is throwing this error?

I did have something like this. I would get an error on the source code saying it the object was undifined when it was trying to put the tooltip on the treenode. To 'fix' it I turned off script debuging on my browser, and it went away.

It may be something to try

Eric Wild


Thanks for the suggestion but I don't think that the problem can be solved by suppressing the errors from the browser.

What I would like to know is if other people have had the same problems as myself.

Is this a problem with the AJAX Beta 2? or my silly code?


I am encountering this issue right now and know it is related to the Visible="false" on the TreeView.

I'm using RC1 and have a Button in an UpdatePanel and a TreeView in another UpdatePanel. The TreeView has it's Visible property = "false".

When the Button is clicked, it sets TreeView's Visible="true".

At this point, if you try to Expand a TreeView Node, it will come back with that same debugging trap you encountered. I tried using Fiddler to see if it passed anything, but it didn't.

You could either keep the TreeView's Visible property = "true" from the start or set the TreeView's EnableClientScript="false".

I think this deserves a bump and hope someone can further explain why and perhaps offer a workaround because the concept that the TreeView only populates its expanding Node is very nice.

Nathan

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 ModalPopupExtender from LoadPage Event instead of Control

Is it possible to have the modal dialog appear when a page is first loaded? It appears that it only works from a control (TargetControlID) like a button.

Create a LinkButton that has style="display: none;" and make this the target control of the ModalPopup. Then call the server side Show() or the client side show() method to display the modal popup manually whenever you need to.

Saturday, March 24, 2012

Trigger problem

Hello, I have an custom control with an event, Something like this

Partial

Class CustomControl_SearchInherits System.Web.UI.UserControl

End Class

Therein i have declared an event:

PublicEvent SelectedIndexChanged(ByVal senderAsObject,ByVal eAs System.EventArgs)

and in the html i have created an Listbox

<ASP:ListboxSelectionMode="Multiple"ID="_Listbox"runat="server"AutoPostBack="true"Height="100%"Width="400px"/>

then on the event Listbox.selectedIndexChanged i raise the event SelectedIndexChanged.

ProtectedSub Listbox_SelectedIndexChanged(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles _Listbox.SelectedIndexChanged RaiseEvent SelectedIndexChanged(sender, e)EndSubNow when i try to hook up a selectedIndex event (from my custom control) on the TRIGGER property from the update panel, it wont work, Why not?, It doesnt even apear in the event property's of my custom control

Could you specify the control composition?

I mean , whether the update panel holds an instance of your CustomControl_Search, or the ListBox itself.

If it is the first case, it is quite natural that the update panel cannot be triggered by the SelectedIndex event of the list box.

Probably you could paste some more code here ?

Yani


Ok. Here is some more code:

This is the definition of the custom control

<%@.ControlLanguage="VB"AutoEventWireup="false"CodeFile="Search.ascx.vb"Inherits="CustomControl_Search"%>

<tablewidth="100%"height="100%"cellspacing="0"cellpadding="0"border="0"id="TableNav">

<trheight="12px">

<tdrowspan="4"style="width: 400px"class="IL">

<ASP:ListboxSelectionMode="Multiple"ID="_Listbox"runat="server"

Height="100%"Width="400px"/></td>

</tr>

</table>

ProtectedSub Listbox_SelectedIndexChanged(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles _Listbox.SelectedIndexChanged

RaiseEvent SelectedIndexChanged(sender, e)

EndSub

PartialClass CustomControl_Search

Inherits System.Web.UI.UserControl

' declare events

PublicEvent SelectedIndexChanged(ByVal senderAsObject,ByVal eAs system.EventArgs)

PublicEvent Find_Clicked()

' handle event (in customcontrol)

ProtectedSub Listbox_SelectedIndexChanged(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles _Listbox.SelectedIndexChanged

RaiseEvent SelectedIndexChanged(sender, e)

EndSub

EndClass

Then I use this custom contol in an aspx page, with 4 update panels, witch have a trigger on the SelectedIndexChanged event raised by Searchpnl

<tdcolspan="3"><uc4:SearchID="Searchpnl"runat="server/></td>

<cc1:UpdatePanelID="UpdatePanel1"runat="server"RenderMode="Inline">

<ContentTemplate>

-- Content --

</ContentTemplate>

<Triggers><cc1:ControlEventTriggerControlID="Searchpnl"EventName="SelectedIndexChanged"/></Triggers>

</cc1:UpdatePanel>

But I the whole page is updated, and I won't only the update panel to be updated. (that's where its for).

I can't see the SelectedIndexChanged event in the property's. I can't see it in the task pane from the updatepanel either.

Thanks in advance


If you want to get only the update panel updated, you need to put your search control into the update panel.

Other wise it wouldn't know whether to make a regular page post back or an ajax one.

If it does not work try registering your search control in the script manager

ScriptManager1.RegisterAsyncPostBackControl(Searchpnl);

Cheers,

Yani


While we work closely with the ASP.NET AJAX team when developing the Toolkit, they're the real experts on general ASP.NET AJAX issues. Your problem doesn't seem to be directly related to the Toolkit, so we'd appreciate if you considered posting to one of theother newsgroups such asAJAX Discussion and Suggestions. Your post will be more helpful to others looking for similar advice if it's in the right place. Thank you!

hi,

how can an activex control trigger an event of the parent form's control?

for example, I have an activex control which is a button that when clicked, it will output the content of a textbox.

Public Function setText(txt As String)
msg = txt
End Function

Private Sub Button_login_Click()
MsgBox msg

End Sub

After the msgbox is displayed, I want to clear the text in the textbox located in the parent form.

Any idea?

thanks!

Sheila

Trigger set to a userControl controls event

Hi Everyone,

I am pretty new to atlas and I am trying to figure out if it can do what i want it to do. I have a gridview control and a user control on a page. The user control has a button that I would like to have trigger the update panel on the aspx webform for the gridview.

When I do this I get a control ID not valid exception on the page. Is there a way to do this or am i only dreaming of better days?

Thanks

Calvin X

Is this not possible or nobody knows?

Were you able to figure this out? I am contemplating performing the same task, so I am interested if you have had some success.

Thank you!

Triggering an updatepanel

Is it possible to trigger an updatepanel from a dropdown list's selectedindexChanged event? The dropdown list will also be in an updatepanel to prevent a complete postback. How would I go about doing this? Any help would be appreciated.

Thanks in advance!

Hi Oak29,

Since the DDL is on the updatepanel, you just need to set the following property of the DDL: autoPostBack = true

Let me know if this worked out!

Kind regards,
Wim


hi,

Yes, it is possible to trigger an updatepanel from a a dropdown list's selectedindexChanged event.

If dropdownlist is in same updatepanel then I think you do not require trigger.

Let me know if you have any issue.


That's what I was forgetting! Thanks a million!

Triggering un UpdatePanel update event from TreeView

Hi!

I have a master page with a TreeView, which is filled from a SiteMapDataSource. I have added an UpdatePanel, inside which i have placed a ContentPlaceholder. I have created an AsyncPostBackTrigger which looks like this:

<asp:AsyncPostBackTrigger ControlID="NavigationTreeView" EventName="SelectedNodeChanged" /
The problem is that the postback is still executed everytime i click on a node,making the UpdatePanel useless.

I have tried disabling treeview postbacks, by changing the Node.Text to <span onclick='return false;'>" + tempNodeLabel + "</span>";
But in this case, the SelectedNodeChanged event does not happen.

What i want in a nutshell is to make the content of a page update without fully reloading the page,while using TreeView as a trigger.

I have heard that TreeView doesn't support partial page updates.

Can anyone suggest how can i make treeview support it or how to disable postbacks while leaving SelectedNodeChanged event,or how can i achieve the desired result in any other manner?

Can anyone help please?

I'm using the treeview triggering/updating other updatepanels this way:

1. The treeview is in an updatepanel and there is the same asyncpostbacktrigger as your inthat updatepanel.

2. I handle theSelectedNodeChanged event in code behind, and update the necessary updatepanels with theupdate( ) method.

Step 1. is not supported officially.

The treeview "may works" inside the up, but very buggy and has strange/unexpected behavior, prepare for some surprise...Smile


Thank you for an adviceSmile

But i'm a bit confused. The SelectedNodeChanged event happens only if the navigateurl property of a node is blank. In this case, how do i pass the URL which has to be shown to the UpdatePanel?


Ok, i've placed the TreeView inside an UpdatePanel and postbacks don't happen as long as the navigateurl property is blank. The only thing i don't get is how to let the UpdatePanel know about the url's it has to show.

Each treenodebinding has a valuefield property (This value is not displayed to the user it's hidden on the page.).

If you set it then you can retrive the value in the code-behind:

YourTreeView.SelectedNode.Value --> the selected node value property.

YourTreeView.SelectedNode.ValuePath --> each node value separated by the treeview PathSeparator from the root to the selected node.


Thank you

I have thought about this. But what i really don't understand is how to tell the updatepanel, which hosts the ContentPlaceHolder what to load.

On the SelectedNodeChanged event, i get the url from the Value field, and then what? To whom should i pass that url?


Sorry, but you cannot use up that way. The up won't load a content from an url (from a different aspx) page.


You may have tried this already and are looking for an alternate way, but this is surely a case for an iframe..

Add an iframe to the page ( don't see why you can't place this inside your updatepanel) and set the selected url to the 'src' attribute of the iframe. This will then load the target content into the iframe, and the update panel should allow you to control the partial postback (not sure if you will need it as the postback from the iframe will be containted within it's own page).


Thank you both for the helpSmile

My boss has told me today that what i'm trying to do is a wrong way to use AJAX, so i guess that this issue is resolved. The idea with an iframe is good thoughSmile


Hi,

Here 's what I do:

1. The "leaf" nodes are calling javascript function that updates a HiddenField.

2. The Grid is inside a UpdatePanel and has a Trigger on the HiddenField ValueChanged event.

To activate the HiddenField trigger, I call _doPostBack('hiddenfield_name', ''); at the end of the javascript function...

Hope it helps,

Michel


Hi,

Hmm..i'm not too good at javascript. If i get it right, what you are suggesting is a way to update a gridview e.g. make it show another category. I have managed to do that but with datalist in my case. I just put an index of a category inside the Value field of a treenode, and leave the navigateurl blank. On page_load event i check which node is selected and if something is selected a read it's Value field and then call a function which retrieves content from the database, depending on the fetched index.

What i was trying to do was to load a completely different page with another set of controls via UpdatePanel. But as far as i understood you can't do that (well maybe if you use an iframe you can)Smile


Then maybe the "update panel" is not ideal to load a different page.

If the tree is in a "master page", you could use a simple hyperlink to load a different "content page"...

Sorry, I got mixed-up by the thread subject.

Triggering TextChanged event

I'm trying to get a textbox to trigger it's textchanged event and post back via atlas - my code is as follows:

<atlas:ScriptManagerID="sm1"runat="server"EnablePartialRendering="true"/>

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

<ContentTemplate>

<asp:TextBoxID="TextBox1"runat="server"OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

</ContentTemplate>

<Triggers>

<atlas:ControlEventTriggerControlId="TextBox1"EventName="TextChanged"/>

</Triggers>

</atlas:UpdatePanel>

It doesn't work! Is this something that should work? I've tried also doing it with a timer which does create a postback, but my textbox loses it's focus everytime.

I've tried looking for posts relating to this but the search functionality on these forums doesn't seem to allow you to restrict searches to specific forums any more.

I wonder if anyone else has tried this or has any suggestions?

Thanks

hello.

i might be wrong, but i think that the trigger should only be used to refresh a panel based on the change of a property or event of another control that is placed *outside* of the updatepanel. when i look at your code, i see that the textbox is inside of the panel. in this case, i think that you only need to set up the textchanged event (btw, don't forget to set the autopostback prop of the textbox to true or the event won't fire!)

I've tried my code both with and without a trigger, and with the text box outside and inside of the update panel - none of these work - in all cases it expects the Return key to be pressed to trigger the postback.

Has anyone got any ideas what I'm doing wrong here, or is this functionality not present?

Think we need ScottGu to the rescue?


hello again.

have you set the autpostback property to true on the textbox? if you don't set that property you won't get an automatic postback when the value of the control is changed.

Yes, autopostback is set - but it only triggers when I press return. I'd hope if would trigger the textchanged event whenever a key was pressed in the text box and cause an Atlas postback.

Also I see on Scott's examples that he is able to directly reference a control that's inside the control template - I had to use FindControl to get to mine - any idea why this is?

I'd be grateful if someone could try this and see if I'm doing something wrong - here's my code:

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

<atlas:ScriptManagerID="sm1"runat="server"EnablePartialRendering="true"/>

<asp:TextBoxID="TextBox1"runat="server"OnTextChanged="TextBox1_TextChanged"AutoPostBack="True"></asp:TextBox>

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

<ContentTemplate>

<h1>

<asp:LabelID="Label1"Text="Waiting for first postback"runat="server"></asp:Label>

</h1>

</ContentTemplate>

</atlas:UpdatePanel>

</form>


hello again.

well, the textchanged event only fires when the textbox looses its focus. so, if you hit tab after changing the value of the textbox you should also get a postback.

regarding your second question about getting a control, can you give us more info on what you're trying to do?

thanks.

Wednesday, March 21, 2012

Trouble Retaining values entered or selected for controls inside an update panel

Hi,

Trouble in retaining values of dropdownlist, textboxes, and other controls when dropdownlist selectedindexchanged event is triggered, the controls are inside a user
control and this user control inside a parent user control with an update panel. Can you guys help me hwo to retain the values. I have set EnableViewState to true. Where
is correct page event to store entered and selected values before the values on controls are re-intialized. Please provide some codes and please eb specific unto which is best to use (Session variables, hiddenfields or others). Thanks in advanced.

den2005

Can you please actually provide code you are using and getting the issue with. Otherwise here are some links:

http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx


Hi jodywbcb,

I am working on 5 dropdownlist controls (these codes are created by a co-worker) and they are some how interdependent, first dropdown and second dropdown and third dropdown determines the data for fourth and fifth dropdown, now second dropdown determines the data for third dropdown. The thing is if the first dropdown is set to item 2, and second dropdown is set to to item2 and data selected on third dropdown remains set after postback.

Here at some data I am working on...So what mistake I have made..

protected override void OnLoad(EventArgs e){...this.UpdateContent();base.OnLoad(e);if (multiView.GetActiveView().ID =="viewInputForm"){if (Session["id"] !=null)ShowAssessmentDetails(Session["id"].ToString());DisplayProcessedIconImage();}}//All Dropdown SelectedIndexChanged Eventprotected void DropDown_SelectedIndexChanged(object sender, EventArgs e){if (sender ==this.ddlEmployee){...}else if (sender ==this.ddlCategory){FillSubCategoryList();FillCompetencyList();}else if (sender ==this.ddlSubCategory){if (ddlSubCategory.SelectedIndex != 0){int subcat = Int32.Parse(ddlSubCategory.SelectedValue);ddlCategory.SelectedValue = oAssessment.GetCategoryID(subcat);FillSubCategoryList();ddlSubCategory.SelectedValue = subcat.ToString();if (subcat.ToString() !=string.Empty && subcat.ToString() !="0")ViewState["ddlSubCategory"] = subcat.ToString();}FillCompetencyList();}else if (sender ==this.ddlCompetencyCode){UpdateCompetencyList(1);DoCourseCodeMatching();}else if (sender ==this.ddlCompetency){UpdateCompetencyList(2);DoCourseCodeMatching();}else if (sender ==this.ddlCourseCode){ClearSuggestedTrainingData();//FillTrainingData();DoCourseCodeMatching();}else if (sender ==this.ddlYear){...}else if (sender ==this.ddlCompetencyModel){FillCategoryList();FillSubCategoryList();FillCompetencyList();}...}private void ShowAssessmentDetails(string idVal){oAssessment.ID = Convert.ToInt32(idVal);if (oAssessment.Get()){InitializeControls();...FillCompetencyModelList();//First Dropdown...FillEmployeeData();try { ddlCompetencyModel.SelectedValue = oAssessment.CompetencyModelID.ToString(); }catch { ddlCompetencyModel.SelectedIndex = 0; }FillCategoryList();//Second DropDownFillSubCategoryList();//Third DropdownFillCompetencyList();//Fourth DropdownFillCourseCode();ddlCompetency.SelectedValue = oAssessment.CompetencyID.ToString();UpdateCompetencyList(2);try { ddlCourseCode.SelectedValue = oAssessment.CatalogueCourseID.ToString(); }catch { ddlCourseCode.SelectedIndex = 0; }...FillSupervisorApproval(cbTrainingRequest.Checked);FillLocalApproval(cbTrainingRequest.Checked);ddlCSApproval.SelectedValue = oAssessment.CompetencySupervisorApprovalID.ToString();ddlCLApproval.SelectedValue = oAssessment.CompetencyLocalApprovalID.ToString();...try { ddlSuggLocalTrainingType.SelectedValue = oAssessment.SuggestedLocalTrainingType.ToString(); }catch { ddlSuggLocalTrainingType.SelectedIndex = 0; }tbLocalTrainingSuggest.Text = oAssessment.SuggestedLocalTraining;try{ddlSuggTrainingType.SelectedValue = oAssessment.SuggestedTrainingType.ToString();tbSuggestedTraining.Text = oAssessment.SuggestedTraining;}catch{ddlSuggTrainingType.SelectedIndex = 0;tbSuggestedTraining.Text = String.Empty;}...}}private void InitializeControls(){...FillCompetencyModelList();...FillCategoryList();FillSubCategoryList();FillCompetencyList();FillSupervisorApproval(false);FillLocalApproval(false);...FillCourseCode();...}private void FillCompetencyModelList(){try{using (DataAccessLayer objDAL =new DataAccessLayer("CompetencyModel_GetAllByYear")){objDAL.AddParameter("Year", ddlYear.SelectedValue);objDAL.ExecuteReader();ddlCompetencyModel.Items.Clear();ddlCompetencyModel.Items.Add(new ListItem("-- select model --","0"));while (objDAL.DataReader.Read()){ddlCompetencyModel.Items.Add(new ListItem(MultiLanguageField.GetFieldValue(Convert.ToString(objDAL.DataReader["Name"])), Convert.ToString(objDAL.DataReader["CompetencyModelID"])));}}}catch{ddlCompetencyModel.Items.Clear();ddlCompetencyModel.Items.Add(new ListItem("-- select model --","0"));}}private void FillCompetencyList(){if (ddlCompetencyModel.SelectedIndex != 0){try{ddlCompetencyCode.Items.Clear();ddlCompetency.Items.Clear();ddlCompetencyCode.Items.Add(new ListItem("-- select code --","0"));ddlCompetency.Items.Add(new ListItem("-- select competency --","0"));if (ddlCompetencyModel.SelectedIndex == 0){if ((ddlSubCategory.SelectedValue !=null) && (ddlSubCategory.SelectedValue !="0")){using (DataAccessLayer objDAL =new DataAccessLayer("Competency_GetBySubCategoryIDAndYear")){SqlParameter sqlparam =new SqlParameter("@.subcat", SqlDbType.Int);sqlparam.Value = ddlSubCategory.SelectedValue;objDAL.AddParameter(sqlparam);objDAL.AddParameter("year", ddlYear.SelectedValue);objDAL.ExecuteReader();while (objDAL.DataReader.Read()){ddlCompetencyCode.Items.Add(new ListItem(Convert.ToString(objDAL.DataReader["CompetencyCode"]), Convert.ToString(objDAL.DataReader["CompetencyID"])));ddlCompetency.Items.Add(new ListItem(MultiLanguageField.GetFieldValue(Convert.ToString(objDAL.DataReader["Name"])), Convert.ToString(objDAL.DataReader["CompetencyID"])));}}}else if ((ddlCategory.SelectedValue !=null) && (ddlCategory.SelectedValue !="0")){using (DataAccessLayer objDAL =new DataAccessLayer("Competency_GetByCategoryIDAndYear")){SqlParameter sqlparam =new SqlParameter("@.catid", SqlDbType.Int);sqlparam.Value = ddlCategory.SelectedValue;objDAL.AddParameter(sqlparam);objDAL.AddParameter("year", ddlYear.SelectedValue);objDAL.ExecuteReader();while (objDAL.DataReader.Read()){ddlCompetencyCode.Items.Add(new ListItem(Convert.ToString(objDAL.DataReader["CompetencyCode"]), Convert.ToString(objDAL.DataReader["CompetencyID"])));ddlCompetency.Items.Add(new ListItem(MultiLanguageField.GetFieldValue(Convert.ToString(objDAL.DataReader["Name"])), Convert.ToString(objDAL.DataReader["CompetencyID"])));}}}else{using (DataAccessLayer objDAL =new DataAccessLayer("Competency_GetAllByYear")){objDAL.AddParameter("year", ddlYear.SelectedValue);objDAL.ExecuteReader();while (objDAL.DataReader.Read()){ddlCompetencyCode.Items.Add(new ListItem(Convert.ToString(objDAL.DataReader["CompetencyCode"]), Convert.ToString(objDAL.DataReader["CompetencyID"])));ddlCompetency.Items.Add(new ListItem(MultiLanguageField.GetFieldValue(Convert.ToString(objDAL.DataReader["Name"])), Convert.ToString(objDAL.DataReader["CompetencyID"])));}}}}else if (ddlCompetencyModel.SelectedIndex > 0){if ((ddlSubCategory.SelectedValue !=null) && (ddlSubCategory.SelectedValue !="0")){using (DataAccessLayer objDAL =new DataAccessLayer("Competency_GetBySubCatIDModelYear")){SqlParameter sqlparam =new SqlParameter("@.subcat", SqlDbType.Int);sqlparam.Value = ddlSubCategory.SelectedValue;objDAL.AddParameter(sqlparam);objDAL.AddParameter("year", ddlYear.SelectedValue);sqlparam =new SqlParameter("@.compmodelid", SqlDbType.Int);sqlparam.Value = ddlCompetencyModel.SelectedValue;objDAL.AddParameter(sqlparam);objDAL.ExecuteReader();while (objDAL.DataReader.Read()){ddlCompetencyCode.Items.Add(new ListItem(Convert.ToString(objDAL.DataReader["CompetencyCode"]), Convert.ToString(objDAL.DataReader["CompetencyID"])));ddlCompetency.Items.Add(new ListItem(MultiLanguageField.GetFieldValue(Convert.ToString(objDAL.DataReader["Name"])), Convert.ToString(objDAL.DataReader["CompetencyID"])));}}}else if ((ddlCategory.SelectedValue !=null) && (ddlCategory.SelectedValue !="0")){using (DataAccessLayer objDAL =new DataAccessLayer("Competency_GetByCatIDModelYear")){SqlParameter sqlparam =new SqlParameter("@.catid", SqlDbType.Int);sqlparam.Value = ddlCategory.SelectedValue;objDAL.AddParameter(sqlparam);objDAL.AddParameter("year", ddlYear.SelectedValue);sqlparam =new SqlParameter("@.compmodelid", SqlDbType.Int);sqlparam.Value = ddlCompetencyModel.SelectedValue;objDAL.AddParameter(sqlparam);objDAL.ExecuteReader();while (objDAL.DataReader.Read()){ddlCompetencyCode.Items.Add(new ListItem(Convert.ToString(objDAL.DataReader["CompetencyCode"]), Convert.ToString(objDAL.DataReader["CompetencyID"])));ddlCompetency.Items.Add(new ListItem(MultiLanguageField.GetFieldValue(Convert.ToString(objDAL.DataReader["Name"])), Convert.ToString(objDAL.DataReader["CompetencyID"])));}}}else{using (DataAccessLayer objDAL =new DataAccessLayer("Competency_GetAllByModelYear")){objDAL.AddParameter("year", ddlYear.SelectedValue);SqlParameter sqlparam =new SqlParameter("@.compmodelid", SqlDbType.Int);sqlparam.Value = ddlCompetencyModel.SelectedValue;objDAL.AddParameter(sqlparam);objDAL.ExecuteReader();while (objDAL.DataReader.Read()){ddlCompetencyCode.Items.Add(new ListItem(Convert.ToString(objDAL.DataReader["CompetencyCode"]), Convert.ToString(objDAL.DataReader["CompetencyID"])));ddlCompetency.Items.Add(new ListItem(MultiLanguageField.GetFieldValue(Convert.ToString(objDAL.DataReader["Name"])), Convert.ToString(objDAL.DataReader["CompetencyID"])));}}}}}catch{ddlCompetencyCode.Items.Clear();ddlCompetency.Items.Clear();ddlCompetencyCode.Items.Add(new ListItem("-- select code --","0"));ddlCompetency.Items.Add(new ListItem("-- select competency --","0"));}}else{ddlCompetencyCode.Items.Clear();ddlCompetency.Items.Clear();ddlCompetencyCode.Items.Add(new ListItem("-- select code --","0"));ddlCompetency.Items.Add(new ListItem("-- select competency --","0"));}}private void FillSubCategoryList(){try{if ((ddlCategory.SelectedValue !=null) && (ddlCategory.SelectedValue !="0")){using (DataAccessLayer objDAL =new DataAccessLayer("CompetencySubCategory_GetByCategoryID")){SqlParameter sqlparam =new SqlParameter("@.CatID", SqlDbType.Int);sqlparam.Value = ddlCategory.SelectedValue;objDAL.AddParameter(sqlparam);objDAL.ExecuteReader();ddlSubCategory.Items.Clear();ddlSubCategory.Items.Add(new ListItem("-- select subcategory --","0"));if (ddlCompetencyModel.SelectedIndex != 0){while (objDAL.DataReader.Read()){ddlSubCategory.Items.Add(new ListItem(MultiLanguageField.GetFieldValue(Convert.ToString(objDAL.DataReader["Name"])), Convert.ToString(objDAL.DataReader["CompetencySubCategoryID"])));}}}}else{using (DataAccessLayer objDAL =new DataAccessLayer("CompetencySubCategory_GetAll")){objDAL.ExecuteReader();ddlSubCategory.Items.Clear();ddlSubCategory.Items.Add(new ListItem("-- select subcategory --","0"));if (ddlCompetencyModel.SelectedIndex != 0){while (objDAL.DataReader.Read()){ddlSubCategory.Items.Add(new ListItem(MultiLanguageField.GetFieldValue(Convert.ToString(objDAL.DataReader["Name"])), Convert.ToString(objDAL.DataReader["CompetencySubCategoryID"])));}}}}// Even with/without these codes below still the sameif (ViewState["ddlSubCategory"] !=null && ddlSubCategory.Items.Count > 1){ddlSubCategory.SelectedValue = ViewState["ddlSubCategory"].ToString();ddlSubCategory.SelectedIndex = ddlSubCategory.Items.IndexOf(ddlSubCategory.Items.FindByValue(ViewState["ddlSubCategory"].ToString()));}}catch{ddlSubCategory.Items.Clear();}}


The first thing that comes to mind is your InitializeControls() method...

I see alot of "..." so not sure what that is comenting out...and probably irrelevant

However:

I would do this:

private void InitializeControls()
{
...

If (!Page.IsPostback)

{
FillCompetencyModelList();
...
FillCategoryList();
FillSubCategoryList();
FillCompetencyList();
FillSupervisorApproval(false);
FillLocalApproval(false);
...
FillCourseCode();

}
...
}

It appears you are always re-initializing your data which is not necessary...and may be always setting all of your databound controls to the initial page load values...

However your viewstate issue - you are never actually setting any viewstate values so:

// Even with/without these codes below still the same
if (ViewState["ddlSubCategory"] !=null && ddlSubCategory.Items.Count > 1)
{
ddlSubCategory.SelectedValue = ViewState["ddlSubCategory"].ToString();
ddlSubCategory.SelectedIndex = ddlSubCategory.Items.IndexOf(ddlSubCategory.Items.FindByValue(ViewState["ddlSubCategory"].ToString()));

}

1. You do not need to set the ddlSubCategory.Selected Value and SelectedIndex both at the same time...

2. Do not use the Viewstate of the control to try and re-select the controls select item - it may work but the whole point of the Events when the ddl is selectedindex changed is to already give you that value (in otherwords it is already selected)...in other words that code is not warranted or needed and nor will it ever actually do anything...

now if you were selecting a value in the ddlSubCategory based on say ddlSubCategory_Other then you would do this:

ddlSubCategory.SelectedValue = ddlSubCategory_Other.SelectedValue (if they matched values wise otherwise you would have to loop through the items and determine what should be selected..based on whatever matching criteria you have.)

Suggestions:

Do not reference viewstate for your selected index or values and definately do not try to use both SelectedIndex and SelectedValue...

Code Sample:

For instance here is a simple DDL that populates a string with a mode name:

modeName = dropFilterBy.SelectedValue.ToString();

{do something with it}

Now if I want to keep the modeName in viewstate this is what I would do...

publicstring modeName

{

get

{

return (string)ViewState["modeName"] !=null ?

(

string)ViewState["modeName"] :"Unknown";

}

set { ViewState["modeName"] =value; }

}

That allows me to use the ModeName in code to reference values and not call the dropFilterBy.SelectedValue.ToString(); for proccessing in other areas of the code where I may need the value...

Again the infinitesloop link I responded with earlier - he has two great series on viewstate and understading controls - easy to read and will shed even more info on how to properly use viewstate....and how the page life cycle all works...


jodywbcb:

The first thing that comes to mind is your InitializeControls() method...

I see alot of "..." so not sure what that is comenting out...and probably irrelevant

I think for this part of problem the values of 5 dropdownlist control they are irrelevant, because they are for other sections of the user control.

jodywbcb:

However:

I would do this:

private void InitializeControls()
{
...

If (!Page.IsPostback)

{
FillCompetencyModelList();
...
FillCategoryList();
FillSubCategoryList();
FillCompetencyList();
FillSupervisorApproval(false);
FillLocalApproval(false);
...
FillCourseCode();

}
...
}

It does not work, the data is still not retain, no change in situation

jodywbcb:

It appears you are always re-initializing your data which is not necessary...and may be always setting all of your databound controls to the initial page load values...

Hmmm...the child user control is inside an update panel control(Atlas control) of the parent user control, if I do not repopulate the data then after postback there will be no data.

jodywbcb:

However your viewstate issue - you are never actually setting any viewstate values so:

// Even with/without these codes below still the same
if (ViewState["ddlSubCategory"] !=null && ddlSubCategory.Items.Count > 1)
{
ddlSubCategory.SelectedValue = ViewState["ddlSubCategory"].ToString();
ddlSubCategory.SelectedIndex = ddlSubCategory.Items.IndexOf(ddlSubCategory.Items.FindByValue(ViewState["ddlSubCategory"].ToString()));

}

1. You do not need to set the ddlSubCategory.Selected Value and SelectedIndex both at the same time...

2. Do not use the Viewstate of the control to try and re-select the controls select item - it may work but the whole point of the Events when the ddl is selectedindex changed is to already give you that value (in otherwords it is already selected)...in other words that code is not warranted or needed and nor will it ever actually do anything...

now if you were selecting a value in the ddlSubCategory based on say ddlSubCategory_Other then you would do this:

ddlSubCategory.SelectedValue = ddlSubCategory_Other.SelectedValue (if they matched values wise otherwise you would have to loop through the items and determine what should be selected..based on whatever matching criteria you have.)

Suggestions:

Do not reference viewstate for your selected index or values and definately do not try to use both SelectedIndex and SelectedValue...

Don't follow you here, I just trying both lines of code to solve the problem..no difference.

jodywbcb:

Code Sample:

For instance here is a simple DDL that populates a string with a mode name:

modeName = dropFilterBy.SelectedValue.ToString();

{do something with it}

Now if I want to keep the modeName in viewstate this is what I would do...

publicstring modeName

{

get

{

return (string)ViewState["modeName"] !=null ?

(

string)ViewState["modeName"] :"Unknown";

}

set { ViewState["modeName"] =value; }

}

That allows me to use the ModeName in code to reference values and not call the dropFilterBy.SelectedValue.ToString(); for proccessing in other areas of the code where I may need the value...

Again the infinitesloop link I responded with earlier - he has two great series on viewstate and understading controls - easy to read and will shed even more info on how to properly use viewstate....and how the page life cycle all works...

Don't exactly follow you on this, are you telling not to use viewstate of control but use a ViewState object? Any other ideas?

This part of page appears when a user clicks a button either add/edit "item" link inside a Gridview.

Thanks for the reply..

Dennis


Forgot to add..

CompetencyModel

Category

SubCategory

2 more data

When Category is set to Item2, Item 1 is "-- select a category --", when I change the selected value on SubCategory, the value is retain after postback, but when Category is set to any other values or other dropdown values changes, the values is not being retain..

Please advise for ideas.


Correction previous issues, it seems when Dropdown 1 is set to a default value not item1 and so as Dropdown 2, values are being retain after postback, otherwise no values are retain... So, how do I retain values?

Trouble with $addHandler and return values.

I'm using $addHandler to wire up a keydown event to a TextBox control, like such:

function pageLoad() {
$addHandler($get('TextBox1'), "keydown", TextBox1_KeyDown);
}
function TextBox1_KeyDown(eventArgs) {
if (eventArgs.keyCode == 13)
return false;
}

If I explicitly specify OnKeyDown attribute of the TextBox, this works. However, when I add it using $addHandler, it acts as though the return value isn't being passed back through. I set a breakpoint on the conditional and verified that it is correctly returning false, but the browser submits anyway.

Is there any way to make a "KeyDown" handler using $addHandler that'll pass the function's return value through to the element?

Hi,

did you try with evt.preventDefault() ?


I wasn't familiar with that method. I just tried it like this:

function pageLoad() {
var evt = new Sys.UI.DomEvent($get('TextBox1'));
evt.preventDefault();
}
It didn't seem to have any effect either way. Am I doing that wrong?

Hi,

sorry, I don't understand what you're trying to do in the previous snippet. I was referring to the first snippet you posted, which could be modified as follows:

$addHandler($get('TextBox1'),'keydown', function(evt) {
if(evt.keyCode === 13) {
evt.preventDefault();
}
});
The preventDefault method should prevent the default action for a DOM event from being performed.
That's perfect. Thanks!