Showing posts with label controls. Show all posts
Showing posts with label controls. Show all posts

Wednesday, March 28, 2012

Accordian - How to refer to contained controls in code behind?

Hi,

If i put regular asp.net controls into an accordian pane they are not visible in the code behind file. In other words i cant get mydropdown.selectedvalue if mydropdown is contained in an accordian pane because the compiler will complain that mydropdown doesn't exist? My work around has been to put content into user controls and put the ascx's into the content panes but is this standard practise?

Thanks

Richard

Hi Richard,

Since the AccordionPanes can be databound, they implement theINamingContainer interface and you're unable to access them directly in your code behind. You can work around this withDropDownList list = MyAccordion.FindControl("MyDropDown") as DropDownList;.

Thanks,
Ted

Accessing Wizard controls from client-side Javascript

Hello, all. Thank you in advance for taking the time to read this. I know it is of questionable relevance given that the Wizard control is not an AJAX toolbox component, but since the Wizard is more useless without AJAX, I am hoping it is close enough to topic.

I am dealing with a Viewstate issue that is forcing me to use ScriptingServices for most of my async communications in order to keep round-trip bandwidth manageable. I want to be able to validate entries made on a long wizard both on-the-fly and at-once. But using ScriptServices, I need to access the values in the Wizard controls from client-side.

Trouble is, I have found that the wizard controls and their values are only visible to the DOM if the wizard page is active. Elements on non-active pages are totally inaccessible from client-side.

For example, a textbox with ID=TextBox1 is on page 1 of the wizard control ID=Wizard1; ID=TextBox2 is on page 2 of Wizard1

when Wizard1.ActiveStepIndex equates to page 1, then $get("TextBox1") works, but $get("TextBox2") does not.

I am assuming that there is some object reference to Wizard1 that can be used client-side to get the values from control on non-active pages, but I just can't seem to find it.

If anyone has experience with this and can tell me how to access these values, I would be highly appreciative.

Thank you again for the time, and in advance for any information you can provide.

Hi,

That's because only content of active step will be rendered. Though, all of them will be encoded and saved in ViewState.

My suggestion is use hiddenFields out of the wizard to keep the value of different steps, and they will be always generated and persisted.


Thanks again for your time and thoughts. That's exactly how I have decided to handle it. It sure adds a lot of complication to what seemed like a pretty easy control. Add to it that I am replacing long dropdown lists with static values after a selection has been made to trim the viewstate, and I think it would have been easier to start from scratch.

The hidden fields work great -- very good idea.

Thanks again!

Accessing values from dynamically created controls

Hi. I'm writing a web application that uses Atlas todynamically create controls in a specific section of a web page. I have 2 update panels. One of them contains a DropDownList. The other one will contain thedynamically created controls. The controls are created in the SelectedIndexChanged event of the DropDownList, and I coded that in the server side. All those controls are arranged in a table server control, which is also created in the SelectedIndexChanged event. The page also has a Button server control that will allow me to start processing the values entered by the user in the created controls. Of course this processing will be done in the server side. This button is not part of either update panel.

Now, the problem is that when I try to get the values of the controls in the Button Click server event, using the table.FindControl() function, I see that the table itself is null, so I cannot access any control value. I think the problem has to do with the fact that the table and its controls are created in the update panel, and for some reason everything created there is not available for my Button Click server event.

How can I solve this scenario?

Thanks,

Julio

Modifying the controls colletion during a postback is generally not a good idea in ASP.NET. Additionally, dynamically added controls will not persist through viewstate so you'll have to re-create and add them to the container on each postback.

Instead of adding/removing controls, I suggest you use the "Visible" property of the control. You can set the control.Visible=false, which will prevent it from rendering down to the client.

Hope this helps,

-Tony


Thanks a lot Tony. The problem is that the user can choose 25 different elements in my combobox, and each element will require to create/show from 1 to 20 new controls on the dynamic section of the page. So if I take your advise and just put all possible controls on the page on design view, hidding or showing them asappropriate, wouldn't it be too much overhead for my page?

Julio


Julio,

Any way you choose is going to require quite a bit of code on your end to determine when to show/hide or create/destroy controls. You are correct in that should you choose to instantiate all controls on the page load, it will indeed add extra overhead.

To acheive the results you are looking for, you'll need to test for which item is selected, and fill the update panel accordingly. The earlier this happens in the page lifecycle the better off you are. The one problem you might encounter is that replacing a control on the fly like this, could cause viewstate errors since the control which saved its viewstate in the previous response, has now been replaced with a completely different control.

We've actually built the behavior you're looking for directly into the Infragistics WebTab. It provides LoadOnDemand behavior though an AJAX mechanism. Using a Tab Interface also speeds up the development since you can separate your content into individual tabs, displaying only the relevant tab. In most cases the performance overhead incurred is well worth the development time saved. Of course, you'd need to make that call based on your own project requirements.

Hope this helps,
-Tony


Hi Tony. You are completely right. I have just found that viewstate error you mention. I have tried to control that error, but I just keep getting errors when adding/removing controls. I would like to try using Infragistics WebTab, as our company has full licenses for the NetAdvantage suite. Could you please show me a small example of how could I achieve this behavior with the WebTab and the LoadOnDemand behavior? Or maybe give me a link to an example? I would reallyappreciate it.

Thanks a lot for your help,

Julio


Hi Julio,

You'll need to getNetAdvantage 2006 Volume 2 if you don't already have it. On the WebTab, set AsyncMode=On, and AsyncOptions.EnableLoadOnDemand=True. Next, using the interactive design surface, simply drag and drop your content into the desired Tab pane. You can even switch between tabs by clicking the desired tab on the design-surface. The WebTab has UpdatePanel-like behavior built directly into it, so postbacks will automatically be turned into AJAX callbacks. The LoadOnDemand behavior will also enable the initial page load to contain only the content for the selected tab, all other tab content will be dynamically retrieved as necessary.

Hope this helps,
-Tony


Hi Tony. It seems likeUltraWebTabAJAX features won't help me. Theasync behavior I'm looking for starts outside the tab control, but not in the tabs itself. My UltraWebTab has 25 tabs inside it. I also have a dropdownlist which is outside my UltraWebTab. Now, without any AJAX behavior, what my page does is that, when you select an element in the dropdownlist I hide all the tabs except for the one that is related to the selected value on the dropdownlist. This of course causes a full roundtrip to the server.

So, what I'd like to happen is that, when I change my selection on the dropdownlist, all the not related tabs just become invisible, but with no roundtrip. I enabled all the async options you mentioned, but I thing they are mostly targeted for the scenarios where the user navigates between tabs, and no with my particular scenario. So I just thought I could solve this by adding an Atlas UpdatePanel and putting the UltraWebTab inside it. I also added a trigger to the panel so that any time the dropdownlist change its value, the updatePanel would update its contents.

Here is the code for my DropDownList:

<table>

<tr>

<tdstyle="width: 3px"valign="top">

<asp:DropDownListID="MyDropDownList"runat="server"AutoPostBack="True"DataSourceID="MyDataSource"DataTextField="Description"DataValueField="Id"></asp:DropDownList><asp:ObjectDataSourceID="MyDataSource"runat="server"SelectMethod="GetMyItems"TypeName="MyProduct.MyClass"></asp:ObjectDataSource></td>

</tr>

</table>

...And this is the code for the UltraWebTab and the UpdatePanel:

<table>

<tr><tdstyle="width: 239px; height: 101%;"valign="top"><atlas:UpdatePanelID="Up1"runat="server"Mode="conditional"><ContentTemplate><igtab:UltraWebTabID="MyUltraWebTab"runat="server"BorderColor="#949878"BorderStyle="Solid"BorderWidth="1px"ThreeDEffect="False"SelectedTab="16"AsyncMode="On"><DefaultTabStyleBackColor="#FEFCFD"Font-Names="Microsoft Sans Serif"Font-Size="8pt"ForeColor="Black"Height="22px"><PaddingTop="2px"/></DefaultTabStyle><Tabs>

<!--Here comes my Tabs and controls -->

</Tabs><RoundedImageFillStyle="LeftMergedWithCenter"HoverImage="[ig_tab_winXP2.gif]"LeftSideWidth="7"NormalImage="[ig_tab_winXP3.gif]"RightSideWidth="6"SelectedImage="[ig_tab_winXP1.gif]"ShiftOfImages="2"/><SelectedTabStyle><PaddingBottom="2px"/></SelectedTabStyle><BorderDetailsColorBottom="90, 120, 160"ColorRight="90, 120, 160"/><AsyncOptionsEnableLoadOnDemand="True"/></igtab:UltraWebTab></ContentTemplate><Triggers><atlas:ControlValueTriggerControlID="MyDropDownList"PropertyName="SelectedValue"/></Triggers></atlas:UpdatePanel></td>

</tr>

But now I'm just getting an "Unknown Error" popup window every time I change my selection in the dropdownlist. It seems like any combination of UltraWebTab and UpdatePanel just does not work. I have already written Atlas apps with my current installation (June CTP) and they work fine until I add an UltraWebTab. All Atlas configurations in the web.config and the script manager are on place, so it should work.

Is there a known compability issue between UltraWebTab and UpdatePanel? If it is, is there any way I could achieve my desired behavior with UltraWebTab async and loadOnDemand options?

Thanks a lot,

Julio


Hi Julio,

You should contact Infragistics Developer Support and provide them the details above. A hotfix was made available on Friday, July 28th which may address this issue.

-Tony

Accessing the pages server controls during webmethod calback

Hi,

Tell me please, when we call a webmethod during a callback, we send parameters through the javascript and dom to the webmethod on the server, right?

What if on the server I want, not only to access parameters sent from the javascript calling function, but I also want to acccess controls of the page, like other controls that didnt request the callback, like a gridview control or asp:textbox control, controls that re located on the page but that have nothing to do with the callback call.

Thanks a lot for your help.

PageMethods are static methods and have no access to controls on the page. However the client-side callback can access the DOM.

Accessing controls within in an Accordion ?

Hi all,

A simple problem : I can't get access by to a control placed within a Accodion pane.

More exactly, code completion in C# is giving me the name of the component (a Literal within a Pane of an Accordion) but at runtime I get an error (null reference), the Literal is not created, whatever the moment I try to catch it.

I tried a lot of different events (of the Page, of the Accordion..), I tried to use FindControl instead of direct acces to "Literal1", all failled..

I need to dynamicaly load the content of a Pane when the Page is rendered. I generaly use a Literal since I inject html code. What is the trick to access an asp control within an Accordion Pane ??

Thanks in advance for your help.

The easiest solution would be using FindControl(). Have a look at the following example:

.aspx page:

<%

@.PageLanguage="C#"%>

<%

@.RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="ajaxCT" %>

<!

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"/>

<

body><formid="form1"runat="server"><asp:ScriptManagerID="smr"runat="server"></asp:ScriptManager>

<

ajaxCT:AccordionID="Accordion1"runat="server"><Panes><ajaxCT:AccordionPaneID="AccordionPane1"runat="server"><Header>Header-1</Header><Content>

<asp:GridViewID="GridView1"runat="server"></asp:GridView>

</Content></ajaxCT:AccordionPane></Panes>

</

ajaxCT:Accordion></form>

</

body>

</

html>

.cs file(code behind):

protectedvoid Page_Load(object sender,EventArgs e)

{

GridView myGridView = AccordionPane1.FindControl("GridView1")asGridView;

myGridView.DataSource= myDataTable; // myDataTable is defined somewhere else

myGridView.DataBind();

}

Hopefully this would be helpful.

Cheers.

Sazzad

Accessing controls within an Accordion for UpdatePanel triggers

HI All,

I have an accordion control, which contains a treeview control in one of its panels. I would like to use some of the events for that treeview control as a trigger for an update panel on the same page. Works fine without the Accordion, but when I use the Accordion, I receive an error notifying me that the treeview doesnt exist (I assume because the Accordion control hides it from the source engine).

Any thoughts on how to get around this?

Thanks

Rob

Hey,

I find that I run into this alot. Basically when you have a template control, then the child controls aren't directly accessible from the code behind. Instead you need to get the parent control and call parent.FindControl("name"). Then use this instance to make changes. If this doesn't work or make sense, post an example.

Accessing Controls outside Update Panel.

Hello,

I am having a webapplication in which i am having two pages. w1.aspx and popup.aspx,

On w1.aspx I am having a Menu control and a UpdatePanel control (Ajax Control) and then under Update panel i am having a link named SigIN and a button named refresh,On the click of SignIN l;ink the popup.aspx opens which provides functionality to signin , On that popup window i am logging user in using ajax so there is no refresh in that popup when user signing in.

Now after user signin succefully from the popup.aspx page that is a popup window i am displaying a messge to the user there that "You are SignIN succesfully and now close this window"

When user close the popup window then user comes on the w1.aspx , Now i want when user press the Button Refresh that is present on the w1.aspx under updatepanel control.. then the text of first menu item in the menu control that is present on the page w1.aspx but not under updatepanel will be changed from SignIN to SignOUT, and the link label that is present on this page under updatepanel will be hidden after the click of this refresh button,

But the problem is on the click of this refresh button the link will be hidden but the text of the menu item is not changing. That is i am not able to acces the controls that are present outside the updatepanel control.

WHY??

is it possible to acces the control properties present outside the UpdatePanel control on the click of a button that is present under UpdatePanel control.

????????

Hi, you must to place any control that an another control on UpdatePanel changes on another UpdatePanel. Controls on UpdatePanel can′t to change controls outside UpdatePanel (Don′t happens an error, just don′t works). Don′t need to be the same UpdatePanel. Can be another one, but must be inside of UpdatePanel.


Hi mgodoy_desenv,

Can u please provide me a sample code for the same.

Thanks in Advance...


My codes are very big, so I will to try show. I don′t speak English so much, so excusive for my way of writing:

In code below, you have a control inside UpdatePanel and another one outside:

<html>
...
<asp: Textbox ID="Textbox1" runat="server"/>
...
<asp: UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server"/>
</ContentTemplate>
</asp: UpdatePanel>
</html
To Button1 to change the Text property of Textbox1, Textbox1 must to be placed inside of an UpdatePanel. You not will have an error if that don′t to happen. Just don′t works.

To work, the Textbox1 must be a place inside of an UpdatePanel. The good news is that it don′t need be inside of same UpdatePanel. It can be placed inside another one.

The code below corrects the problem:

<html>
...
<asp: UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>

<asp: Textbox ID="Textbox1" runat="server"/>
</ContentTemplate>
</asp: UpdatePanel>

...
<asp: UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server"/>
</ContentTemplate>
</asp: UpdatePanel>
</html>


Hi,

Your idea is working for a single page but when i am working with master page and menu then i think its not working properly.

Wht i am doing is,

I am having a webpage w1.aspx which is using the master page m1.master, Now my master page having a menu. I want to update the value of that page from the w1.aspx on the click of a button that is present under an updatepanel on w1.aspx.

Now as you said take the control inside the update panel whose value you wann update, so i have taken the menu control under the update panel and then by taking the refrence of menu control on the page w1.aspx i am updating the value of the menu items. But after updatiing the values when i am moving the mouse over the menu items then it gives me the error. some javascript error. I d't know why this ?

If u can then try to do the same thing as i said... with master page..and menu contriol

....


There are many problems with use of UpdatePanel. We must be carefully with it, cause asynchronous post back uses many JavaScript. I haved, for example, many problems with Server.Transfer and UpdatePanel.

Your case isn′t diferent. UpdatePanel can has updated the menu control in a wrong way. Try do this:

1. Use a DataSource to menu. Create a method to populate it with a DataTable, or Xml.
2. When you to want to change items of menu control, change the DataSource (DataTable, or Xml) and call DataBind method of menu.

I don′t speak English so much. So, excuse me for my way of writing.


The Menu control is one of the few ASP.NET controls that isnot compatible with async postbacks. Seehttp://asp.net/AJAX/Documentation/Live/overview/UpdatePanelOverview.aspx#UpdatePanelCompatibleControls for reference.

I would think you should leave the Menu controloutside of the UpdatePanel, but make it a trigger for the UpdatePanel you want to update with <asp:UpdatePanel ...><Triggers><asp:AsyncPostBackTrigger ControlID="MyMenu" /></Triggers>...</asp:UpdatePanel>.


Actually, rereading the question, I may have missed the point here... I was assuming the Menu control was the one triggering the update, but that some other control on the page was being updated.

If the Menu control is the one you want to update, I think you're out of luck, since the Menu can't live inside an UpdatePanel.

Accessing controls inside an updatepanel in onPreInit event

I have an update panel inside a user control that is initialized during the page's PreInit event. However, as soon as I put an updatepanel inside this user control I can no longer access the controls inside this updatepanel during the PreInit event. The controls are all just "null". Am I doing something wrong, or does the updatepanel somehow change my ability to access these controls?Thanks,Jon

Set a breakpoint in PreInit and step through the PageLifeCycle then you see in what Event the UpdatePanel get initialized.


I was just wondering why putting an updatepanel in would break my existing code? Shouldn't it get initialized at the same time as the other controls?
Please have a look at Wally'sPodcast about the clientside lifecycle. I think he's awnsering youre questions.

Accessing controls in a tab control using javascript

Hi ,

Im my project im using tab control.I wat to access the controls inside the content template using javascript.

How is this done?

Anyone please help.

Thanks n regards

Prathibha

prathibhaa:

Im my project im using tab control.I wat to access the controls inside the content template using javascript.

You need to know the client id of the control you want to access. You can get the client id of the control using the ClientID property.

Then in javascript you do this

document.getElementById(<id of control>) to get reference to the control


i tried it.

I have a textbox "txtEmpCode" placed in the content template of tab control.then i tried to access it as follows

document.getElementById("txtEmpCode")

But im getting null value


prathibhaa:

I have a textbox "txtEmpCode" placed in the content template of tab control.then i tried to access it as follows

document.getElementById("txtEmpCode")

Because the text box is in the tab control it may get a different client ID. Best way to check is to view the HTML source on the rendered page and look for the exact ID.

Alternatively you can go textbox.ClientID to get the client rendered ID of the text box control.


i tried this code

document.getElementById("<%=txtEmpCode.ClientID%>")

But I am getting an exception

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Description:Anunhandled exception occurred during the execution of the current webrequest. Please review the stack trace for more information about theerror and where it originated in the code.

Exception Details:System.Web.HttpException:The Controls collection cannot be modified because the control containscode blocks (i.e. <% ... %>).

Source Error:

An unhandled exception was generated during the execution of thecurrent web request. Information regarding the origin and location ofthe exception can be identified using the exception stack trace below.


Stack Trace:

[HttpException (0x80004005): The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).]
System.Web.UI.ControlCollection.Add(Control child) +127
AjaxControlToolkit.ScriptObjectBuilder.RegisterCssReferences(Control control) in d:\E\AjaxTk-AjaxControlToolkit\Release\AjaxControlToolkit\ExtenderBase\ScriptObjectBuilder.cs:293
AjaxControlToolkit.ScriptControlBase.OnLoad(EventArgs e) in d:\E\AjaxTk-AjaxControlToolkit\Release\AjaxControlToolkit\ExtenderBase\ScriptControlBase.cs:260
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Control.LoadRecursive() +158
System.Web.UI.Control.LoadRecursive() +158
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3036

Please help

Thanks and regards

prathibha


prathibhaa:

i tried this code

document.getElementById("<%=txtEmpCode.ClientID%>")

But I am getting an exception

Where are you adding that code to?

You can always just inject the javascript doing this

StringBuilder sb =new StringBuilder();sb.Append("function getTextBox()");sb.Append("{");sb.Append("var textbox;");sb.Append("textbox = document.getElementById();");sb.Append("return textbox;");sb.Append("}");ClientScript.RegisterClientScriptBlock(this.GetType(),"mytextboxscript", sb.ToString());//now you have a javascript function that returns the textbox




Hi Prathibha,

prathibhaa:

document.getElementById("<%=txtEmpCode.ClientID%>")

But I am getting an exception

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Description:An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

That's because you put the document.getElementById("<%=txtEmpCode.ClientID%>") in the wrong position. For example,

<head id="Head1" runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function getName(){

var labelValue = "<%=Label1.ClientID %>";
}
</script>
</head>

<body>
You will get the same error. So you should put it at the end of your form(or other proper position). By the way, you can use$get instead of document.getElementById() if you have added a ScriptManager before. They are the same but is much terser.

Best regards,

Jonathan


hi Jonathan,

Thank you.

can u please tell me where i have to give the javascript and how?

i got the javascript correctly when i gave the client id directly.

regards

Prathibha

Accessing Controls From JavaScript

What is the syntax for accessing control form javascript? I can't seem to find it anywhere - I thought it was something like

dunction HideOne(n)

{

var ele = Sys($(n))

}

not a lot to go on with what you have provided but...

assuming that "n" in this context is the id of an element you want to "access" or get then you should use "$(n)"
to avoid issues with that statement... in your example you would remove the Sys() part and only have the $(n) part

this all depends on, however, how you are creating your elements. if you are using the xml-script declarative approach then you might be better off using the $object() function.
the $object() function searches the current markup context for the element, then traverses the tree up to the Application level to try to find the element.
this is different than the $() function which is nothing more than a shortcut for "document.getElementById()"

this allows the ATLAS runtime to have (or support) multiple elements with the same "id" without violating the HTML 4.1 specifications stating "an elements id must be unique" which it clearly would be (in the current context)

hope that helps... if not try adding some more of your code so we can get a better understanding of what you are dealing with


That was perfect thanks.

accessing controls from diff updatepanels

Hi

Just wondering is it possible to access controls from diff update panels

I have a treeview in 1 updatepanel, upon selecting a node in the tree I want to display a panel outside the updatepanel, possibly in another updatepanel

confusing? maybe

Dim panel1 As Panel = CType(Me.UpdatePanel1.FindControl("panel10"), Panel)

Panel1.Visible = True

It definately finds the contro, but will not mae it visible

thoughts ?

Hi!

Are you calling UpdatePanel1.Update() after you set the visible property to true? If you are missing that the Panel will be "visible" but not "showing" as visible.

Also, just a doubt: Why you need to use FindControl to find controls inside UpdatePanels? They aren't NamingContainers, thus you should be able to call them directly from the page.

Regards,

Juan


One more note: if you're talking about using a TreeView, note that the TreeView control isn't compatible with partial rendering (so it can't get updated inside an UpdatePanel). Seehttp://ajax.asp.net/docs/overview/UpdatePanelOverview.aspx#UpdatePanelCompatibleControls.

A good way to think about the UpdatePanel is that it doesn't really change the way postbacks work. So if you can do what you want to with a regular postback, then it should just be a matter of wrapping the write regions of the page in UpdatePanels and setting up the triggers (or calling UpdatePanel1.Update() in the code-behind) to make sure those regions of the page get updated when appropriate during the async postback. My advice would be to get this working how you want with regular postbacks, then add UpdatePanels (which will by default all update on every async postback), and finally optimize by setting UpdateMode="Conditional" and setting up your triggers, so you selectively update the parts of the page that you need to.


thanks guys , some great advice there

UpdatePanel1.Update() was the key here


Steve Marx:

One more note: if you're talking about using a TreeView, note that the TreeView control isn't compatible with partial rendering (so it can't get updated inside an UpdatePanel). Seehttp://ajax.asp.net/docs/overview/UpdatePanelOverview.aspx#UpdatePanelCompatibleControls.

Steve , Is this something that will be fixed in future AJAX releases

I also have some file upload controls on the page that I really need to have there

Accessing Controls embedded in panel within hoverMenuExtender

I have a Panel with labels inside. I need to add more labls dynamically on run time depending what is returned from a database. This panel is referenced by the hoverMenuExtender. The problem is, is that I cant access any of the panels ID's in the code behind. You can see from the code below in lines 23-42. I need to add more labels there dynmically depending on what is returned from the database on Page_Load.
  
1 <asp:DataList ID="DataList1" runat="server" AlternatingItemStyle-BackColor="ivory"2 CellPadding="5" RepeatColumns="5" Width="92%">3 <HeaderTemplate>4<!-- <table id="RepeaterTable1" border="0">5 <tr>6 <th>ID</th>-->7 <b>8 <asp:Label ID="lblTime2" runat="server"></asp:Label></b>9<!--<th>IP</th>-->10 </tr>11 </HeaderTemplate>12 <ItemTemplate>13<!-- <tr>14 <td><%#Container.DataItem("ID")%></td>-->15 <asp:Panel runat="server" ID="panelMain">16 <asp:Image ID="Image1" runat="server" Height="21px" ImageUrl='<%#Container.DataItem("imgName")%>'17 Width="21px" />18    19<%#Container.DataItem("ServerName")%>20 </asp:Panel>2122 <asp:Panel ID="hovPanel" runat="server" BackColor="black" Width="300px" ForeColor="white">23 <asp:Image ID="hovImage" runat="server" Height="21px" ImageUrl='<%#Container.DataItem("hovIconPing")%>'24 Width="21px" />  <asp:Label runat="server" ID="hovDisk" text='<%#Container.DataItem("hovPing")%>' />25 <br />26 <asp:Image ID="Image3" runat="server" Height="21px" ImageUrl='<%#Container.DataItem("hovIconPhy")%>'27 Width="21px" />  <asp:Label runat="server" ID="Label2" text='<%#Container.DataItem("hovPhy")%>' />   <asp:Label runat="server" ID="Label3" text='<%#Container.DataItem("hovPerPhy")%>' />28 <br />29 <asp:Image ID="Image4" runat="server" Height="21px" ImageUrl='<%#Container.DataItem("hovIconVirt")%>'30 Width="21px" />  <asp:Label runat="server" ID="Label4" text='<%#Container.DataItem("hovVirt")%>' />   <asp:Label runat="server" ID="Label5" text='<%#Container.DataItem("hovPerVirt")%>' />31 <br />32 <asp:Image ID="Image2" runat="server" Height="21px" ImageUrl='<%#Container.DataItem("hovIconDiskOne")%>'33 Width="21px" />  <asp:Label runat="server" ID="Label1" text='<%#Container.DataItem("hovDiskOne")%>' />   <asp:Label runat="server" ID="Label10" text='<%#Container.DataItem("hovPerOne")%>' />34 <br />35 <asp:Image ID="Image5" runat="server" Height="21px" ImageUrl='<%#Container.DataItem("hovIconDiskTwo")%>'36 Width="21px" />  <asp:Label runat="server" ID="Label6" text='<%#Container.DataItem("hovDiskTwo")%>' />   <asp:Label runat="server" ID="Label9" text='<%#Container.DataItem("hovPerTwo")%>' />37 <br />38 <asp:Image ID="Image6" runat="server" Height="21px" ImageUrl='<%#Container.DataItem("hovIconDiskThree")%>'39 Width="21px" />  <asp:Label runat="server" ID="Label7" text='<%#Container.DataItem("hovDiskThree")%>' />   <asp:Label runat="server" ID="Label8" text='<%#Container.DataItem("hovPerThree")%>' />40 <br />41 <asp:Image ID="Image7" runat="server" Height="21px" ImageUrl='<%#Container.DataItem("hovIconCPU")%>'42 Width="21px" />  <asp:Label runat="server" ID="Label11" text='<%#Container.DataItem("hovCPU")%>' />   <asp:Label runat="server" ID="Label12" text='<%#Container.DataItem("CPUPer")%>' />4344 </asp:Panel>45 <ajaxToolkit:RoundedCornersExtender ID="rnd" runat="server" TargetControlID="hovPanel" Radius="6" />46 <ajaxToolkit:HoverMenuExtender ID="HoverMenuExtender1" runat="server" PopupControlID="hovPanel" TargetControlID="PanelMain" OffsetX="0" OffsetY="0" PopDelay="50" PopupPosition="bottom">47 </ajaxToolkit:HoverMenuExtender>4849 </ItemTemplate>50 <FooterTemplate>51<!--</table>-->52 </FooterTemplate>53 </asp:DataList>

And you say that you *can* reference the panel Id's when you're not using an UpdatePanel?I've frequently had trouble finding controls when they're part of a collection inside another control, even previous to ajax extensions work.

Typically, I've resorted to iterating over the items collection of the datalist to do it, using the syntax DataList1.Items[i].FindControl("controlId") to hook into it as you iterate.


But I ned to "Add" a control (label) to the datalist item template. how do I do this? I can do a DataList1.Items[i].FindControl("controlId"), but how do I add items to the list? Thanks for the reply by the way. I am on a short time table here. :)

Right, well, my point is that you're trying (I thought) to add a new label to that one panel that's got a bunch of labels on it, right? to do that, you need to first get an instance of the Panel (iterating over the control tree and returning the one you want). Then, you'd add it to that panel's control collection just like you normally would add a dynamic control, e.g. myPanel.Controls.Add(someLabelYouJustCreated);

Can I ask, though, what's the lifespan of these labels? Because, if they only last as long as the page is in view to the user, it might be easier to add them as clientside objects rather than serverside ones. Just soemthing to think about.


Thanks for the fast reply. You are right that I am trying to add labels dynamically to the panel inside the datalist. I get the intellisense for the datalist, but in the code behind it did not register (intellisense see) the panel. I cant do it on client side because the labels I am filling is coming from a database. So when I type hovPanel.xxx.xxx it says that hovpanel is not declared. thats where my problem is coming from.

I guess I need to get an instance of the panel, but I cant. I tried creating a new one in the code behind with the same name and it runs fine, but nothing gets added to the panel

i.e.

Dim hovpanel as panel = new panel (Although there is already a panel in the .aspx with the ID of "hovpanel"


Right, that's my whole point about the FindControl method. I don't do VB very well, so let me speak in abstract terms. you should say Dim hovPanel as Panel = findPanel("hovPanel") (or some such). findPanel() is a method you define which loops through the items of datalist1 to look for one with the id matching the above; I previously described this.

http://samples.gotdotnet.com/quickstart/aspplus/doc/webdatalist.aspx

That's a good example as well.


Ahh, I see where you are going. Thanks. I am going to give it a try.

Thanks Paul. I did this and it worked...

Dim lbl1As Label =New Label lbl1.Text ="PRINT ME"Dim yAs Integer For y = 0To DataList1.Items.Count - 1Dim hovpanelAs Panel = DataList1.Items(y).FindControl("hovpanel") hovpanel.Controls.Add(lbl1)Next
Now within the "FOR" loop and can run tests to see how many labels are there and how many to add and what not. Thanks a Million !!! :)


Glad I could help.

Monday, March 26, 2012

Access User Controls in Web Service

Hello all,

We have a custom control that has many custom properties and methods. Currently this control is being loaded through the Master page and it is working just fine. Now there is a need to load this control through a web service.

Since the control needs to be loaded through a web service, the web service does not have any information on this custom control and its properties/methods. We can only load this custom control as a System.Web.UI.UserControl, and we cannot also cast this UserControl as a custom control because the web service does not know anything about this custom control.

I read this article about rendering user controls through web service by Scott Gutherie but it only talks about user control and not custom controls and custom properties and methods.

http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx

Does anybody have any ideas on how to access the custom control in a web service?

Thanks.

Hi,

For custom control, it's necessary to add reference to it in the web application. And instantiate it with its actual constructor.

Then, you may render it in a similar way as Scott Gutherie has shown.

Access the control in Tabpanel on TabpanelContainer?

My second tab have some controls, ex. Textbox1, how can i access the value of Textbox1 in Tabpanel2 ?

Thanks,

I believe that Textbox1.Text should work for you... but I cannot try because I'm on diferent machine.


Hi,

Here is an example of referencing it with the help of FindControl method.

<%@. Page Language="C#" %><!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_Init(object sender, EventArgs e)
{
TextBox tb = Panel2.FindControl("TextBox1") as TextBox;
tb.Text = DateTime.Now.ToString();

}

</script
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div><asp:Button runat="server" Text="Button" ID="Button1"></asp:Button>
<ajaxToolkit:TabContainer runat="server" Height="150px" ID="tbcPlanOverview" >
<ajaxToolkit:TabPanel runat="Server" ID="Panel1" HeaderText="Tab One">
<ContentTemplate>
PAGE ONE - Sample HTML Content for Tab
</ContentTemplate>
</ajaxToolkit:TabPanel>
<ajaxToolkit:TabPanel runat="Server" ID="Panel2" HeaderText="Tab Two" >
<ContentTemplate>
PAGE TWO - Sample HTML Content for Tab
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ContentTemplate>
</ajaxToolkit:TabPanel
<ajaxToolkit:TabPanel runat="Server" ID="Panel3" HeaderText="Tab Three">
<ContentTemplate>
PAGE THREE - Sample HTML Content for Tab
</ContentTemplate>
</ajaxToolkit:TabPanel>
</ajaxToolkit:TabContainer> <br />
<asp:Image ID="Image1" runat="server" />
<asp:TextBox ID="txtTabSelect" runat="server" />
</div>
</form>
</body>
</html>

Access Textbox Inside an Atlas CollapsiblePanel

Hello all, I have this code

<%

@dotnet.itags.org.RegisterSrc="~/Controls/CollapsibleContent.ascx"TagPrefix="collapsible"TagName="CollapsibleContent" %>

<collapsible:CollapsibleContentID="generalPanel"IsCollapsed="false"runat="server">
<Title>Datos Generales del Documento</Title>
<Content>
<tablewidth="100%"border="0"cellspacing="0">
<tr>
<tdstyle="text-align: left; width:15%">
<asp:LabelID="lblFormItem1"runat="server"Text="Titulo"></asp:Label>
</td>
<tdstyle="text-align: left; width:25%">
<asp:TextBoxID="txtFormItem1"runat="server"MaxLength="50"Width="85%"Enabled="false"></asp:TextBox>
<asp:RequiredFieldValidatorID="RequiredFieldValidator3"runat="server"ControlToValidate="txtFormItem1"ErrorMessage="this is a required field, can't be null"ValidationGroup="Page">*</asp:RequiredFieldValidator>
</td>
</tr>
</table>
</Content>
</collapsible:CollapsibleContent>

I'm trying to access the value of the textbox but when I build my solution, the debuger send that the txtFormItem1 doesn't exist, I have tried to do this

TextBox txt1 = (TextBox)this.Page.FindControl("txtFormItem1");
if (txt1 !=null)
{
txt1.Enabled = !txt1.Enabled;
}

Can anyone help me please. Thanks.

Try

generalPanel.FindControl("txtFormItem1");


I haven't tryed to reproduce your issue but feel questions:

Why are you using FindControl if you haven't instantiated the control dynamicly? just access txtFormItem1.Text...

if it doesn't work, download the latest release from codeplex... an issue about blank textboxes was resolved...

Hope helped...

Regards,

Felipe Oquendo
MCAD


sburke_msft:

Try

generalPanel.FindControl("txtFormItem1");

it would work too...

Access is denied

Hi..

I have aspx page, and this page contain iframe. In the Iframe i try to open aspx page that contain ajax controls like animation, progress bar... the problem that i have is: when i try to move my cursor on the image that open the animation box, i get the following error: Access is denied.

When the progress bar is starting to work i get the same error..so, in each control that i am using i get this error..and i don't know how to solve this..

thank you...

The "Access Denied" error in any browser usually means that a script in one window or frame is trying to access another window or frame whose document's domain is different from the document containing the script. What can seem odd about this is that you get this error in IE for Windows frequently when a script in one window generates a new window (withwindow.open()), and content for that other window is dynamically created from the same script doing the opening. Thefocus() method also triggers the error.

The error can also occur if scripts try to access objects, properties, or methods that have been locked down by Microsoft's security platoon. For instance, thedocument.styleSheets.rules property used to be accessible in IE 5 and IE 5.5, but is not in IE 6.

For the new window problem, there is a bit of history associated with the problem and workarounds. For example, the problem occurs frequently when the scripts are being run from the local hard disk. You get a clue about the situation in the titlebar of the new window: It forces anabout:blank URL to the new window, which is a protocol:domain that differs from wherever your main window's script comes from. If, however, you put the same main window document on a server, and access it via http:, the problem goes away.

There is a workaround for the local-only problem: In the first parameter of thewindow.open() method call, load a real document (even if it is a content-free HTML document) into the sub-window before usingdocument.write() to generate content for the subwindow. The loading action 'legitimizes' the window as coming from the same domain as your main window's document.

(This solution does not affect scripts that load a page from a secure server into a separate window or frame. Anhttp: protocol in one window andhttps: in the other--even if from the same server.domain--yield a security mismatch and "Access Denied." Setting thedocument.domain properties of both pages may solve the problem (but I am unable to test it for sure).)

For other situations (such as thedocument.styleSheets.cssRules problem, there are no workarounds, so you'll have to find another way around your task.

One more source of this error in IE occurs if you assign a too-long search string to a URL or a form (using the GET method) has lots of elements and data. The HTTP GET method has a built-in limit of approximately 512 characters. If you run into the problem, change the method to POST, which has no data length limit. But POST won't reflect the search string in the URL of the replacement page (in case you're expecting to parse that data as a way to convey data from one page to the next).

Access credentials are not being loaded when use Atlas functionality

Facing this bizzare issue of access denied when use Atlas funcationality. I am using UpdatePanel in two .ascx controls that searches a list(list is on one .ascx and search button is on the 2nd .ascx).Everything works fine(i.e performs search in an Atlas way - no whol page refresh) but it generates an error on the browser that says..

A run time error has occured..

Line: 86762781

Error: Object expected.

When i see the log file at c:/windows/system32/Logfiles/ W3SVC1.. i see

That request is using 127.0.0.1 as the credentials instead of my own credential string.

This is the case if i use Atlas UpdatePanel otherwise it works fine.

Any clue in this regards, do i have to do something in terms of security to get it working?

Copied this Microsoft.Web.Atlas.dll over to my machine and issue went away.

Access controls added dinamically?

Hi:
I trying to access to controls in updatepanel that I createddinamically before with atlas too, and I allways get the error that thecontrol does not exist.
Is there any way to do this?
Thanks so much.Do you have some sample source you can post? In which event handler are you trying to access the controls?
I was tried this with the code in the examples section. With SimpleList1_edit.aspx exactly.
I add a new textbox and a new button to panel3 when I click button ,and it works perfect, but when I click the new button and go to thecode for the code onclick then the findcontrol never finds the controlin the panel. I tried with find in the whole page and only in the panel and never works. This is the code:

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

<%@. Import Namespace="System.Data" %>
<%@. Import Namespace="System.Data.SqlClient" %>

<script runat="server">

protected void Page_Load(object sender, EventArgs e)
{
TimerMessage.Text = DateTime.Now.ToLongTimeString();
if (!IsPostBack)
{
ViewState["CurrentTab"] = "0";
}
}


protected void AddnewBtn_click2(object sender, EventArgs e)
{
TextBox txtbox = (TextBox)FindControl("newtxtbox");
idlbl.Text = txtbox.Text;
panel3.Update();
}
protected void AddnewBtn_click(object sender, EventArgs e)
{


TextBox txtbox = new TextBox();
txtbox.ID = "newtxtbox";
Button btn = new Button();
btn.ID = "newbtn";
btn.OnClientClick = "AddnewBtn_click2";
panel3.Controls.Add(txtbox);
panel3.Controls.Add(btn);
btn.Text = "Read new textbox value";
panel3.Update();

}
protected string FormatPriority(int priority)
{
switch (priority)
{
case 1:
return "Low";
case 2:
return "Medium";
default:
return "High";
}
}

protected string FormatDone(bool isDone)
{
return isDone == true ? "Yes" : "No";
}

protected void Done_CheckedChanged(object sender, EventArgs e)
{
CheckBox cbx = (CheckBox)sender;
GridViewRow row = (GridViewRow)cbx.NamingContainer;
using (SqlConnection cn =newSqlConnection(ConfigurationManager.ConnectionStrings["SimpleListsConnectionString"].ConnectionString))
{
cn.Open();
SqlCommand cmd = new SqlCommand(
"UPDATE Lists SET IsComplete = @.IsComplete WHERE ListId = @.ListId",cn);
cmd.Parameters.Add("IsComplete", cbx.Checked);
cmd.Parameters.Add("ListId", ListGrid.DataKeys[row.RowIndex].Value);
cmd.ExecuteNonQuery();
}
ListGrid.DataBind();
}

protected void Select_Command(object sender, CommandEventArgs e)
{
ListDataSource.SelectParameters["IsComplete"].DefaultValue =
e.CommandArgument.ToString();
if (e.CommandName == "show")
SearchText.Text = "";
ViewState["CurrentTab"] = e.CommandArgument;
panel2.Update();
}

protected void Page_PreRender(object sender, EventArgs e)
{
int i = int.Parse(ViewState["CurrentTab"].ToString());
ActiveButton.CssClass = i == 0 ? "activeTab" : "tab";
CompletedButton.CssClass = i == 1 ? "activeTab" : "tab";
AllButton.CssClass = i == -1 ? "activeTab" : "tab";
SearchTab.Attributes["class"] = i == -2 ? "activeTab" : "tab";
}
protected void Page_ErrorHandler(object sender, PageErrorEventArgs e)
{
e.ErrorMessage = "Exception at " + DateTime.Now.ToString() +
"; Error Message: " + e.Error.Message;
}

</script>

<!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">
<link href="http://links.10026.com/?link=StyleSheet.css" rel="stylesheet" type="text/css" />
<title>Partial Rendering</title>


</head>
<body>
<form id="f1" runat="server">
<atlas:ScriptManagerID="ScriptManager1" EnablePartialRendering="true"OnPageError="Page_ErrorHandler" runat="server">
<ErrorTemplate>
<div style="width: 450px; height: 300px; padding: 10px; border:solid 3px black; background: #ffd; text-align: left;">
<h1>Server Error</h1>
<p>An unhandled exception with the following message has occuredon the server:</p>
<p><span id="errorMessageLabel"runat="server"></span></p>
<p><input id="okButton" type="button" value="OK"runat="server"/></p>
</div>
</ErrorTemplate>
</atlas:ScriptManager>
<atlas:UpdateProgress runat="server" id="updateProgress1">
<ProgressTemplate>
<div style="width: 450px; height:300px;position:absolute; padding: 10px; border: solid 3px black;background: #ffd; text-align: left;">
<img src="http://pics.10026.com/?src=Progress.gif" /> Contacting Server...
<button id="abortButton">Stop</button>
</div>
</ProgressTemplate>
</atlas:UpdateProgress>
<div>
<div id="top">

</div>
<div class="ContentContainer">
<div id="header">
<div id="ServerMessage">
<span class="controlLabel">Server Time:</span>
<asp:Label ID="TimerMessage" runat="server">n/a</asp:Label><asp:Button ID="UpdateTimerMessageBtn" Text="Update" runat="server"/>
</div>
<span class="title"><a href="http://links.10026.com/?link=Default.aspx">SimpleList</a> > Standard Server Page</span>
</div>
<div class="tabs">

<atlas:UpdatePanel ID="panel1" runat="serveR" Mode="Conditional">
<ContentTemplate>
<span class="controlLabel">Show:</span>
<asp:LinkButton ID="ActiveButton" Text="Active" CommandName="show"CommandArgument="0" OnCommand="Select_Command" runat="server" />
<asp:LinkButton ID="CompletedButton" Text="Completed"CommandName="show" CommandArgument="1" OnCommand="Select_Command"runat="server" />
<asp:LinkButton ID="AllButton" Text="All" CommandName="show"CommandArgument="-1" OnCommand="Select_Command" runat="server" />
<span class="controlLabel leftSpace">Search:</span>
<span id="SearchTab" runat="server">
<asp:TextBox ID="SearchText" CssClass="filterdropdown" Width="150px"runat="server" />
<asp:Button ID="SearchBtn" CssClass="topButtons" Text=" >> "
CommandName="search" CommandArgument="-2" OnCommand="Select_Command"runat="server" />
</span>
</ContentTemplate>
</atlas:UpdatePanel>
<!-- Add a closing UpdatePanel tag below here. -->
</div>
<div id="list">

<atlas:UpdatePanel ID="panel2" runat="server" Mode="Conditional">
<ContentTemplate>
<asp:GridView ID="ListGrid" BorderWidth="0px"AutoGenerateColumns="False" DataKeyNames="ListId"
DataSourceID="ListDataSource" AllowPaging="True" AllowSorting="True"EnableViewState="False"
GridLines="None" runat="server">
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"CausesValidation="True" CommandName="Update"
Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server"CausesValidation="False" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="DeleteBtn" runat="server"CausesValidation="False" CommandName="Delete"
Text="Delete"></asp:LinkButton>
</ItemTemplate>
<ControlStyle CssClass="buttons" />
<HeaderStyle CssClass="commands" />
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="List"SortExpression="Name">
<ControlStyle CssClass="name_edit" />
<ItemStyle CssClass="name" />
<HeaderStyle CssClass="name" />
</asp:BoundField>
<asp:TemplateField HeaderText="Priority"SortExpression="Priority">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" Width="75"SelectedValue='<%# Bind("Priority") %>'
runat="server">
<asp:ListItem Text="High" Value="3" />
<asp:ListItem Text="Medium" Value="2" />
<asp:ListItem Text="Low" Value="1" />
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="pri" Text='<%# FormatPriority((int)Eval("Priority")) %>' runat="server" />
</ItemTemplate>
<ItemStyle CssClass="priority" />
<HeaderStyle CssClass="priority" />
</asp:TemplateField>
<asp:BoundField DataField="DateCreated"DataFormatString="{0:MM/dd/yyyy}" HtmlEncode="False"
HeaderText="Started" ReadOnly="True" SortExpression="DateCreated">
<ItemStyle CssClass="started" />
<HeaderStyle CssClass="started" />
</asp:BoundField>
<asp:TemplateField HeaderText="Completed"SortExpression="IsComplete">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%#Bind("IsComplete") %>' />
</EditItemTemplate>
<ItemStyle CssClass="iscomplete" />
<HeaderStyle CssClass="iscomplete" />
<ItemTemplate>
<asp:Label ID="Done" Text='<%# FormatDone((bool)Eval("IsComplete")) %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<span id="Empty">No lists</span>
</EmptyDataTemplate>
</asp:GridView>
</ContentTemplate>
<Triggers>
<atlas:ControlEventTrigger ControlID="AddListBtn" EventName="Click"/>
</Triggers>
</atlas:UpdatePanel>
<!-- Add a closing UpdatePanel tag below here. -->
</div>
<div id="AddNew">

<atlas:UpdatePanel ID="panel3" Mode="Conditional" runat="server">
<ContentTemplate>
<span>Add New List:</span>
<asp:TextBox ID="AddItemTxt" CssClass="newitem"runat="server"></asp:TextBox>
<asp:Button ID="AddnewBtn" runat="server" OnClick="AddnewBtn_Click"Text="Add" />
</ContentTemplate>
<Triggers>
<atlas:ControlEventTrigger ControlID="AddnewBtn" EventName="Click"/>
</Triggers>
</atlas:UpdatePanel>

</div>


</div>
</div>

<asp:SqlDataSourceID="ListDataSource" runat="server" ConnectionString="<%$ConnectionStrings:SimpleListsConnectionString %>"
SelectCommand="SELECT ListId, Name, Priority, IsComplete, DateCreated
FROM Lists
WHERE (@.IsComplete = -1)
OR (@.IsComplete in (0, 1) AND IsComplete = @.IsComplete)
OR (@.IsComplete = -2 AND Name LIKE '%' + @.SearchText + '%')"
UpdateCommand="UPDATE Lists
SET Name=@.Name, IsComplete=@.IsComplete, Priority=@.Priority
WHERE ListId = @.ListId"
DeleteCommand="DELETE FROM Lists WHERE ListId = @.ListId">
<SelectParameters>
<asp:Parameter Name="IsComplete" Type="Int32" DefaultValue="0" />
<asp:ControlParameter Name="SearchText" Type="string"ControlID="SearchText"
PropertyName="Text" ConvertEmptyStringToNull="false" />
</SelectParameters>
</asp:SqlDataSource>

</form>
<hr />
</body>
</html
Thanks for the help.

I've been wondering about this as well. I'd really, really like the ability to do this. I came up with a short test page to validate the issue outside of my site.

The code for the test page is below. Run this, click "Add Control" and a label will be added to the placeholder control. Click "Refresh" and watch the label control vanish. You can also validate in the debugger that the label control added to the placeholder has disappeared (that is, it's not in the controls collection at Page_Load time()).

Is there something obvious I'm overlooking?

--

<%@. Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><script runat="server"> protected void Page_Load(object sender, EventArgs e) { } protected void Add_OnCommand(object sender, CommandEventArgs e) { Label lab = new Label(); lab.Text = "Dynamically added label"; TestPlaceHolder.Controls.Add(lab); } protected void Refresh_OnCommand(object sender, CommandEventArgs e) { }</script><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Dynamically added control test</title></head><body> <form id="form1" runat="server"> <atlas:ScriptManager ID="ScriptManager1" runat="server" /> <atlas:UpdatePanel ID="TestPanel" runat="server"> <ContentTemplate> <asp:PlaceHolder ID="TestPlaceHolder" runat="server"></asp:PlaceHolder> <asp:Button ID="TestAddButton" runat="server" Text="Add Control" OnCommand="Add_OnCommand" /> <asp:Button ID="Refresh" runat="server" Text="Refresh" OnCommand="Refresh_OnCommand" /> </ContentTemplate> </atlas:UpdatePanel> </form></body></html>

^^^ Nevermind. My example didn't state the case correctly. I went back and fixed it and found everything was fine with values updating on dynamic controls.

The problem was in my site with an off-by-one error in control names. With the names corrected, everything is fine.

Access control on MasterPage from within content page

Hi all,

I have a MasterPage with invisible Label.

In content page I have a few controls and any Button.

When user clicks the Button, the Label on MasterPage appears.

So far - so good.

If I use an UpdatePanel inside the content page, the Label stay invisibleSad.

I know, that it's right behavior for Ajax enabled application, but...

What is the solution?

MasterPage:

<%@dotnet.itags.org. Master Language="C#" AutoEventWireup="true" CodeFile="TestMasterPage.master.cs" Inherits="TestMasterPage" %><!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 runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:contentplaceholder id="ContentPlaceHolder1" runat="server"> </asp:contentplaceholder> <asp:Label ID="Label1" runat="server" Text="Error!" Visible="False"/> </form></body></html>

Content page:

<%@dotnet.itags.org. Page Language="C#" MasterPageFile="~/TestMasterPage.master" AutoEventWireup="true" CodeFile="TestContentPage.aspx.cs" Inherits="TestContentPage" Title="Untitled Page" %><asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:ListBox ID="ListBox1" runat="server"> <asp:ListItem Value="1">Item 1</asp:ListItem> <asp:ListItem Value="2">Item 2</asp:ListItem> <asp:ListItem Value="3">Item 3</asp:ListItem> <asp:ListItem Value="4">Item 4</asp:ListItem> </asp:ListBox> <br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> </ContentTemplate> </asp:UpdatePanel></asp:Content>

Content page code behind:

protected void Button1_Click(object sender, EventArgs e) {//Do something... //... Label lbl = (Label)Page.Master.FindControl("Label1");if (lbl !=null) lbl.Visible =true; }

The solution: enclose the Label on the MasterPage by UpdatePanel:

<%@. Master Language="C#" AutoEventWireup="true" CodeFile="TestMasterPage.master.cs" Inherits="TestMasterPage" %><!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 runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:contentplaceholder id="ContentPlaceHolder1" runat="server"/> <asp:UpdatePanel ID="updatePanel2" runat="server"> <ContentTemplate> <asp:Label ID="Label1" runat="server" Text="Error!" Visible="False"/> </ContentTemplate> </asp:UpdatePanel> </form></body></html>

Saturday, March 24, 2012

A tale of two ListControls

I've got two custom server controls that extend ListControl and implement IPostBackEventHandler. Both override RenderContents and both render anchor tags. Both of them use Page.ClientScript.GetPostBackClientHyperlink in order to assign a string value to each anchor which I retrieve upon postback. The only real difference between the two is that one is a horizontal list and one is a vertical list.

I've placed each control within its own webcontrol. Each webcontrol contains an UpdatePanel, and that UpdatePanel's ContentTemplate contains the server conrol I've written. Each UpdatePanel's UpdateMode is set to Conditional.

Here's where it gets weird. When I render the page and click on a hyperlink in the vertical-displaying control, a partial postback occurrs as expected. Both controls update themselves and, when the partial postback returns, both are updated properly.

When I click on a hyperlink in the horizontally-displaying control, a full postback occurrs rather than the partial postback that should have happened. I cannot for the life of me figure out why this is happening.

Again, both controls are almost exactly the same. They render exactly the same, save one places each hyperlink in a div so they are arranged vertically rather than horizontally.

I've placed a button within the horizontally-displaying control's UpdatePanel and when I click on the button a partial postback occurrs as is expected. Still, clicking on one of the hyperlinks within the same UpdatePanel causes a full postback.

I don't even know where to start looking to find out why the full postback is occurring rather than a partial postback. Any help at this point will be greatly appreciated.

Funny how you figure out exactly what was going on right after you post your question...

The problem was that my web control's ID was "crumbs", but I was wrapping my anchor tags within a DIV with a different ID. The postback javascript was prepending that div's ID to the __DoPostBack argument, confusing the update panel. The control layout looked like this:

DIV id="crumbs_updatePanel" (the UpdatePanel's containing DIV)

DIV id="breadCrumbs" (this is where I was screwing up)

A href="http://links.10026.com/?link=javascript:__doPostBack('breadCrumbs$breadCrumbBar','')" (the UpdatePanel was confused by the div id before the $)

By making sure the containing DIV had the same ID as the web control, I made sure that the postback hyperlink had the correct div ID so that the UpdatePanel recognized it.

DIV id="crumbs_updatePanel" (the UpdatePanel's containing DIV)

DIV id="crumbs" (the containing div now has the correct ID)

A href="http://links.10026.com/?link=javascript:__doPostBack('crumbs$breadCrumbBar','')" (the UpdatePanel now recognizes this postback as coming from within itself, and does a partial postback.)

More information on this issue here: http://forums.asp.net/thread/1488508.aspx