Showing posts with label adding. Show all posts
Showing posts with label adding. Show all posts

Wednesday, March 28, 2012

programatically adding cascading dropdowns with the ability to add to the dropdownlist

I'll keep this as simple as possible, apologies in advance. Cascading dropdowns (CCD) are added to a page programatically. Each cascade dropdown (CCD) is added in a while lop based on the number of levels read in from a db table. beside each dropdown (CCD) is an add button, which when clicked pops up a modal window, allowing the user to via an update panel add to each the cascading dropdown (CCD) of choice. My problem is this I want the button beside the dropdown only to become enabled when the cascading dropdown is active/populated. So when I draw everything in theOnInit function I make the buttons beside the cascading dropdowns disabled. My Question is how do I enable them based on the (CCD) becoming active? and secondly am I doing this the correct way. Code below: Thanks in advance

While counter < SR.Item("Annello")

Lit =New Literal

If counter < 1Then

Lit.Text ="Category"

Else

Lit.Text ="Sub-Category"

EndIf

UPanel.ContentTemplateContainer.Controls.Add(Lit)

DDL =New DropDownList

With DDL

.ID ="DropDown" & counter

.Width = 250

.DataTextField ="CategoryName"

.DataValueField ="CID"

EndWith

UPanel.ContentTemplateContainer.Controls.Add(DDL)

Cascade =New AjaxControlToolkit.CascadingDropDown

With Cascade

.ID ="Cas" & counter

.TargetControlID = DDL.ID

If counter > 0Then

.ParentControlID ="DropDown" & counter - 1

.PromptText ="Please select a Sub-Category"

Else

.PromptText ="Please select a Category"

EndIf

.LoadingText ="Loading.."

.Category = counter

.ServiceMethod ="GetCategoriesPageMethod"

EndWith

UPanel.ContentTemplateContainer.Controls.Add(Cascade)

IB =New ButtonWith IB

.ID ="ADD" & counter

.Text ="add to.."

EndWith

UPanel.ContentTemplateContainer.Controls.Add(IB)

IB.Enabled =False

'''MODAL POPUP

NPanel =New Panel

With NPanel

.Style.Add(HtmlTextWriterStyle.Display,"none")

.Style.Add(HtmlTextWriterStyle.Height,"200px")

.Style.Add(HtmlTextWriterStyle.Width,"350px")

.Style.Add(HtmlTextWriterStyle.BackgroundColor,"#ffffff")

.Style.Add(HtmlTextWriterStyle.Padding,"10px")

.ID ="NPanel" & counter

EndWith

Lit =New Literal

Lit.Text ="Enter Your Category here "

NPanel.Controls.Add(Lit)

TBX =New TextBox

With TBX

.ID ="AddTBX" & counter

.Width =New System.Web.UI.WebControls.Unit(190)

EndWith

NPanel.Controls.Add(TBX)

IB =New ButtonWith IB

.ID ="OK" & counter

.Text ="OK"

'.Attributes.Add("onclick", "InsertCategory();")

EndWith

NPanel.Controls.Add(IB)

IB2 =New Button

With IB2

.ID ="Cancel" & counter

.Text ="Cancel"

EndWith

NPanel.Controls.Add(IB2)

UPanel.ContentTemplateContainer.Controls.Add(NPanel)

MP =New AjaxControlToolkit.ModalPopupExtender

With MP

.TargetControlID ="ADD" & counter

.PopupControlID ="NPanel" & counter

.OkControlID ="OK" & counter

.CancelControlID ="Cancel" & counter

.OnOkScript ="InsertNewCategory()"

.OnCancelScript ="alert('cancel');"

'.OnOkScript = "alert('OK');"

.DropShadow =False

.BackgroundCssClass ="ModalPopupBackground"

EndWith

UPanel.ContentTemplateContainer.Controls.Add(MP)

Hi

Try this,It works:

<td><asp:DropDownList ID="DropDown1" onchange="javascript:activeBtn(this)" runat="server" Width="170" /></td>

<script type='text/javascript'>
function activeBtn(ccd)
{
var strcounter = ccd.id.substring(ccd.id.indexOf("DropDown") + 8, ccd.length - 1);
var counter = parseInt(strcounter);
var theBtn = document.getElementById(ccd.id.replace("DropDown", "ADD").replace(strcounter, (counter + 1) + ""))
if(theBtn){
if(ccd.selectedIndex != 0)theBtn.disable = false;
else theBtn.disable = true;
}
}
</script>

You can add the onchange event handlers for your DropDownLists in code-behind by using this code:

DDL =New DropDownList

With DDL

.ID ="DropDown" & counter

.Width = 250

.DataTextField ="CategoryName"

.DataValueField ="CID"

.Attributes.Add("onchange", "javascript:activeBtn(this);")

EndWith

Best Regards


Gave that a go and couldn't get it to work. I see what your doing and I'm hitting the function and even if I hardcode the Button.ID to enable that one button it doesn't work, no errors but it just won't enable it... any ideas. Thanks in advance..


Hi

Sound odd,I have test it many times.I'm sure it works.

Would you please privide us with a whole demo?

Thanks


ThanksJin-Yu YinSmile


Firstly thanks for you help. It is strange that it doesn't work, the funny thing is if I change you function to the following it works, but I'd never have gotten there without your help. Again many thanks.

function activeBtn(ccd)

{

var strcounter = ccd.id.substring(ccd.id.indexOf("DropDown") + 8, ccd.length - 1);

var counter = parseInt(strcounter);

var theBtn = document.getElementById(ccd.id.replace("DropDown","ADD").replace(strcounter, (counter + 1) +""))

if(theBtn){

if(ccd.selectedIndex != 0)

{

if (theBtn.disabled) {theBtn.disabled =false;}else theBtn.disabled =true;

}

}

}


Hi

Glad to hear that it works now.I'm sorry for misunderstanding any logic of it.

Best Regards


Like I said mate, thanks ,u were 100% bang on. Appreciate the help.

Programatically Adding an AutoCompleteExtender & AutoCompleteProperties

This is from the documentation:

To extend a text box with auto-completion behavior programmatically, add an AutoCompleteExtender control to your ASP.NET Web page, and use theServicePath andServiceMethod properties to specify the Web method that returns the item list. Then for each text box that you want to add the auto-completion behavior to,add anAutoCompleteProperties server control to theControls collection of the AutoCompleteExtender. The AutoCompleteProperities component enables you to specify the target control the extender should link to and to override the ServicePath and ServiceMode setting for individual controls.

So am I to understand that I add an AutoCompleteProperties instance to the AutoCompleteExtender.Controls collection?

When I try that I get this message in VS2005:

Value of type 'Microsoft.Web.UI.Controls.AutoCompleteProperties' cannot be converted to 'System.Web.UI.Control'.

hello.

well, you just need to add them as child elements of the control since it'll automaticatically parse those elements and add them to the targetproperties property.


...forgive me for my ignorance, but how exactly is that accomplished? Can you provide a brief example?

Thanks! :)


Dim autoComplete as New AutoCompleteExtender()
Dim props as New AutoCompleteProperties()
props.TargetControlID = "txt_suggestion"
props.ServiceURL = "/WebServices/Service.asmx"
props.ServiceMethod = "GetSuggestions"
autoComplete.TargetProperties.Add(props)
Page.Controls.add(autoComplete)

Hey that worked! Thanks!

I didn't know about the AutoCompleteExtender.TargetProperties.Add method, I was trying to add it to the controls collection of the AutoCompleteExtender.

FYI - The ServiceURL property in the above code is supposed to be ServicePath (at least in the July 06 release).

Programatically adding UpdatePanel?

I want to programatically add an updatepanel control on a button click.

I tried adding a reference to Microsoft.Web.Atlas.dll and then creatinga System.Web.UI.UpdatePanel control but the app does not compile - withnamespace does not exist error.

Does anyone know what I should be doing or if this is possible at all?

Thanks !

you would need to import the following

Imports Microsoft.Web.UI

Then, you can create an instance of the UpdatePanel like this:

Dim UP As New UpdatePanel

Hope this works for you.


Thanks it works ... I was using System.Web.UI which was the problem
Now that I have this I'm trying to add content to the updatepanel.

I can set most of the properties, add triggers without problems.

However when I try to execute it - it gives an error saying "A ContentTemplate must be specified".

Whats the easist way to do this. I haven't found any documentation on programatically adding a contenttemplate.

Any help would be greatly appreciated!
I'm looking for the same thing myself and haven't found any answers.
You'll need to create a class that implements ITemplate, create an instance of that and set the content template property to that instance.

try this

protected

overridevoid OnInit(EventArgs e)

{

updatePanel.ContentTemplate =

newCompiledTemplateBuilder

(

newBuildTemplateMethod(CreateAtlasUpdateContent));

}

public

void CreateAtlasUpdateContent(Control container)

{

container.Controls.Add(yourcontrol);

}


dont know if this will come in handy with anyone but what i did to get around the template error was

have a class with the following:

PublicClass AjaxControl :Inherits Microsoft.Web.UI.UpdatePanelProtectedOverridesSub OnInit(ByVal eAs System.EventArgs)Me.ContentTemplate =New TemplateBuilderMyBase.OnInit(e)EndSubEndClass

Then whenever i needed to create a control that was surrounded by the update panel i would inherit this class and could just then put me.controls.add() as usual.

probs useless to you all, but works for me :)


Even if you got past the coding issues, you still can't add an UpdatePanel once InitComplete has fired (which is pretty early in the lifecycle) so you're not going to be able to accomplish what you set out to do, which I think was to add an UpdatePanel dynamically.

HTH

Has anyone been able to dynamically add an UpdatePanel to a page?

I got so far - and then I got the error:

"The UpdatePanel 'panel1'was not present when the page's InitComplete event was raised."

Is there any way around this?

Wade.

Programmatically adding a ConfirmButtonExtender

Hi,

I cannot get my ConfirmButtonExtender to work when I add it from the code behind.

A javascript page error occurs the page loads:

Line: 2829
Char:23
Error: Sys.ArgumentException: Value must not be null for Controls and Behaviors.
Parameter name: element
Code:0

---------------

Here is the code:

-- .asp snippet----

 <asp:ScriptManager ID="ScriptMan1" runat="server"> </asp:ScriptManager> <asp:Panel ID="Panel1" runat="server"> </asp:Panel> 

---.asp.cs snippet----

protected void Page_Load(object sender, EventArgs e) { Button button =new Button(); button.Text ="Click Me"; Panel1.Controls.Add(button); AjaxControlToolkit.ConfirmButtonExtender confirmDeleteExt =new AjaxControlToolkit.ConfirmButtonExtender(); confirmDeleteExt.TargetControlID = button.UniqueID; confirmDeleteExt.ConfirmText ="Are you sure?"; Panel1.Controls.Add(confirmDeleteExt); }

----------

It's nothing special, but what am I missing?!

I am dynamically building the page, so beginning with the button on the page is not an option (which works no problem).

Thanks!

Your code works fine on my computer.


OK,

Thanks for your reply, kipo, looking at it again it seems that the error only seems to occur when using a masterpage.

Does it still work for you if you put all of it into a masterpage?


I've tried to put your code in page which is using MasterPage and it doesn't work, so you were right - error is occuring only with MasterPage. But, you can achieve it with this code:

Button button = new Button();
button.Text = "Click Me";
button.ID = "button1";
Panel1.Controls.Add(button);

AjaxControlToolkit.ConfirmButtonExtender confirmDeleteExt = new AjaxControlToolkit.ConfirmButtonExtender();
confirmDeleteExt.TargetControlID = "button1";
confirmDeleteExt.ConfirmText = "Are you sure?";
Panel1.Controls.Add(confirmDeleteExt);


Excellent!Big Smile

Thanks a lot for your help!

I thought this problem was related to IDs, but is this a bug or is this by design?

Programmatically adding ASP.net User Control to UpdatePanel

Hi All, I got a real doozy here. I have read hundreds upon hundreds of forum posts and found numerous others who have replicated this problem, but have yet to find a solution. Through testing I have been able to find the cause of the problem, and will describe it here first textually and then through a code example.

The purpose of what I am trying to do is to create a postback-free web application through the use of ASP.net AJAX UpdatePanels and User Controls. When programmatically adding a User Control to a web page through a normal postback everything works fine. All the controls within the user control are registered properly in the page and any update panels included in the user control also work properly. HOWEVER, if instead of using a full postback you use an UpdatePanel and a partial page update of the UpdatePanel the controls do not get registered with the page and events from them do not fire (for instance, a button click event never hits the event breakpoint).

Because the very same user control works fine if loaded in a full postback or dynamically added from a namespace works fine, I can be relatively sure that it only is trouble when loading via a partial page update into an UpdatePanel. I load the control via the LoadConrol method and then add it to the page via a PlaceHolder control. Theoretically, adding the User Control to the PlaceHolder should register itself and it's controls and events with the page, but it does not.

The following code sample is a UpdatePanel-free page using a user control that works, later I will show the same code with an UpdatePanel that does not.

I think I need to figure out how to register the controls and their events with the page without going through a full page postback. Any suggestions??

This example works as expected:
Default.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>23<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4<html xmlns="http://www.w3.org/1999/xhtml">
5<head runat="server">
6 <title>Untitled Page</title>
7</head>
8<body>
9 <form id="form1" runat="server">
10 <div>
11 <asp:PlaceHolder ID="UCPlaceHolder" runat="server"></asp:PlaceHolder>
12 </div>
13 </form>
14</body>
15</html>

Default.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
1011public partialclass _Default : System.Web.UI.Page
12{
13protected void Page_Load(object sender, EventArgs e)
14 {
15 Control ctl = LoadControl("~/UserControlDemo.ascx");
16 ctl.ID ="UC1";
17this.UCPlaceHolder.Controls.Add(ctl);
18 }
19}

UserControlDemo.ascx:
1<%@dotnet.itags.org. Control Language="C#" AutoEventWireup="true" CodeFile="UserControlDemo.ascx.cs" Inherits="UserControlDemo" %>2<asp:Button ID="Button1" runat="server" Text="Display from UC" OnClick="Button1_Click" /> <br />
3<br />
4<asp:Label ID="Content" runat="server" Text="Content"></asp:Label>

UserControlDemo.ascx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
1112public partialclass UserControlDemo : System.Web.UI.UserControl
13{
14protected void Page_Load(object sender, EventArgs e)
15 {
16 }
17protected void Button1_Click(object sender, EventArgs e)
18 {
19 Content.Text ="Content Changed.";
20 }
21}

Now, consider this variation, where instead of loading the control in the PageLoad event, you do so programmatically via a button Click event. This does not work as it cause a full postback which refreshes the placeholder. Viewstate does not seem to be working in this case. (uses the same user control as the previous example)

Default.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>23<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4<html xmlns="http://www.w3.org/1999/xhtml">
5<head runat="server">
6 <title>Untitled Page</title>
7</head>
8<body>
9 <form id="form1" runat="server">
10 <div>
11 <asp:Button ID="Button1" runat="server" Text="Load User Control" OnClick="Button1_Click" />
12 <br />
13 <br />
14 <asp:PlaceHolder ID="UCPlaceHolder" runat="server"></asp:PlaceHolder>
15 </div>
16 </form>
17</body>
18</html>

Default.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
1011public partialclass _Default : System.Web.UI.Page
12{
13protected void Page_Load(object sender, EventArgs e)
14 {
15 }
16protected void Button1_Click(object sender, EventArgs e)
17 {
18 Control ctl = LoadControl("~/UserControlDemo.ascx");
19 ctl.ID ="UC1";
20this.UCPlaceHolder.Controls.Add(ctl);
21 }
22}

To solve this postback problem, one would naturally want to use an UpdatePanel, like the following example. However this does not work as the controls do not seem to get registered with the page, and further nesting of user controls in UpdatePanels (to create a postback free app) are no better.

Default2.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>23<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
45<html xmlns="http://www.w3.org/1999/xhtml" >
6<head runat="server">
7 <title>Untitled Page</title>
8</head>
9<body>
10 <form id="form1" runat="server">
11 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
12 <div>
13 <asp:UpdatePanel ID="UpdatePanel2" runat="server">
14 <ContentTemplate>
15 <asp:Button ID="Button1" runat="server" Text="Load User Control into UpdatePanel" OnClick="Button1_Click" />
16 </ContentTemplate>
17 </asp:UpdatePanel>
18 <br />
19 <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
20 <ContentTemplate>
21 <asp:PlaceHolder ID="ContentPlaceHolder" runat="server"></asp:PlaceHolder>
22 </ContentTemplate>
23 <Triggers>
24 <asp:AsyncPostBackTrigger ControlID="Button1" />
25 </Triggers>
26 </asp:UpdatePanel>
27 </div>
28 </form>
29</body>
30</html>

Default2.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
1112public partialclass Default2 : System.Web.UI.Page
13{
14protected void Page_Load(object sender, EventArgs e)
15 {
1617 }
18protected void Button1_Click(object sender, EventArgs e)
19 {
20 Control ctl = LoadControl("~/UserControlDemo.ascx");//loads into the page21 ctl.ID ="UC1";
22this.ContentPlaceHolder.Controls.Add(ctl);//adds to page control tree (or at least it should)23 }
24}

I know I can use the "visible" property of my controls to toggle them on and off a page to create a flicker free experience, however, my application is a database intensive app and I don't want the page running queries against the database unless I'm absolutely sure the user wants them. Rendering a 10 forms and keeping them hidden isn't a big deal, but running 10 queries that the user never wants to see is, otherwise I'd stick to that method, its works perfectly. Any suggestions? Or requests for clarification? Any help you can provide is much appreciated...thanks, Chris.

Chris, are you still working on this?

I've managed to get partial postbacks to fire events on the server from a button on a UserControl that was loaded as a result of a partial postback by an updatepanel.

Here's the code:

protected override void OnPreInit(EventArgs e){base.OnPreInit(e);if (this.Page.Request.Form["__UCTL"] !=null)this.ChangeControls(this.Page.Request.Form["__UCTL"].ToString(),null);elsethis.ChangeControls("Login","Login");}public void ChangeControls(String controlName, String controlTitle){ScriptManager.RegisterHiddenField(this,"__UCTL", controlName);this.host.ContentTemplateContainer.Controls.Clear();UserControl ctl = (UserControl)Page.LoadControl(CONTROL_DIRECTORY +"\\" + controlName +".ascx");ctl.ID = controlName;this.host.ContentTemplateContainer.Controls.Add(ctl);if (controlTitle !=null)this.host.Page.Title = controlTitle;}

I also created an Interface that has a method of ChangeControls with that signature and had my Page implement it so that my UserControls could get access to the method.


Hi Jason,

I figured out how to do it properly, you need to raise an event from the control and listen for it with the page or another control. The code to do so is also simpler than what you have. Check out this thread for more details: http://forums.asp.net/t/1123449.aspx

Feel free to msg me questions if you are confused.

-Chris

Programmatically adding ASP.net User Control to Partial Page Update / UpdatePanel

Hi All, I got a real doozy here. I have read hundreds upon hundreds offorum posts and found numerous others who have replicated this problem,but have yet to find a solution. Through testing I have been able tofind the cause of the problem, and will describe it here firsttextually and then through a code example.

Thepurpose of what I am trying to do is to create a postback-free webapplication through the use of ASP.net AJAX UpdatePanels and UserControls. When programmatically adding a User Control to a web pagethrough a normal postback everything works fine. All the controlswithin the user control are registered properly in the page and anyupdate panels included in the user control also work properly. HOWEVER,if instead of using a full postback you use an UpdatePanel and apartial page update of the UpdatePanel the controls do not getregistered with the page and events from them do not fire (forinstance, a button click event never hits the event breakpoint).

Becausethe very same user control works fine if loaded in a full postback ordynamically added from a namespace works fine, I can be relatively surethat it only is trouble when loading via a partial page update into anUpdatePanel. I load the control via the LoadConrol method and then addit to the page via a PlaceHolder control. Theoretically, adding theUser Control to the PlaceHolder should register itself and it'scontrols and events with the page, but it does not.

Thefollowing code sample is a UpdatePanel-free page using a user controlthat works, later I will show the same code with an UpdatePanel thatdoes not.

I think I need to figure out how to register thecontrols and their events with the page without going through a fullpage postback. Any suggestions??

This example works as expected:
Default.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4<html xmlns="http://www.w3.org/1999/xhtml">
5<head runat="server">
6 <title>Untitled Page</title>
7</head>
8<body>
9 <form id="form1" runat="server">
10 <div>
11 <asp:PlaceHolder ID="UCPlaceHolder" runat="server"></asp:PlaceHolder>
12 </div>
13 </form>
14</body>
15</html>

Default.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10
11public partialclass _Default : System.Web.UI.Page
12{
13protected void Page_Load(object sender, EventArgs e)
14 {
15 Control ctl = LoadControl("~/UserControlDemo.ascx");
16 ctl.ID ="UC1";
17this.UCPlaceHolder.Controls.Add(ctl);
18 }
19}

UserControlDemo.ascx:
1<%@dotnet.itags.org. Control Language="C#" AutoEventWireup="true" CodeFile="UserControlDemo.ascx.cs" Inherits="UserControlDemo" %>
2<asp:Button ID="Button1" runat="server" Text="Display from UC" OnClick="Button1_Click" /> <br />
3<br />
4<asp:Label ID="Content" runat="server" Text="Content"></asp:Label>

UserControlDemo.ascx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12public partialclass UserControlDemo : System.Web.UI.UserControl
13{
14protected void Page_Load(object sender, EventArgs e)
15 {
16 }
17protected void Button1_Click(object sender, EventArgs e)
18 {
19 Content.Text ="Content Changed.";
20 }
21}

Now,consider this variation, where instead of loading the control in thePageLoad event, you do so programmatically via a button Click event.This does not work as it cause a full postback which refreshes theplaceholder. Viewstate does not seem to be working in this case. (usesthe same user control as the previous example)

Default.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4<html xmlns="http://www.w3.org/1999/xhtml">
5<head runat="server">
6 <title>Untitled Page</title>
7</head>
8<body>
9 <form id="form1" runat="server">
10 <div>
11 <asp:Button ID="Button1" runat="server" Text="Load User Control" OnClick="Button1_Click" />
12 <br />
13 <br />
14 <asp:PlaceHolder ID="UCPlaceHolder" runat="server"></asp:PlaceHolder>
15 </div>
16 </form>
17</body>
18</html>

Default.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10
11public partialclass _Default : System.Web.UI.Page
12{
13protected void Page_Load(object sender, EventArgs e)
14 {
15 }
16protected void Button1_Click(object sender, EventArgs e)
17 {
18 Control ctl = LoadControl("~/UserControlDemo.ascx");
19 ctl.ID ="UC1";
20this.UCPlaceHolder.Controls.Add(ctl);
21 }
22}

Tosolve this postback problem, one would naturally want to use anUpdatePanel, like the following example. However this does not work asthe controls do not seem to get registered with the page, and furthernesting of user controls in UpdatePanels (to create a postback freeapp) are no better.

Default2.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5<html xmlns="http://www.w3.org/1999/xhtml" >
6<head runat="server">
7 <title>Untitled Page</title>
8</head>
9<body>
10 <form id="form1" runat="server">
11 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
12 <div>
13 <asp:UpdatePanel ID="UpdatePanel2" runat="server">
14 <ContentTemplate>
15 <asp:Button ID="Button1" runat="server" Text="Load User Control into UpdatePanel" OnClick="Button1_Click" />
16 </ContentTemplate>
17 </asp:UpdatePanel>
18 <br />
19 <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
20 <ContentTemplate>
21 <asp:PlaceHolder ID="ContentPlaceHolder" runat="server"></asp:PlaceHolder>
22 </ContentTemplate>
23 <Triggers>
24 <asp:AsyncPostBackTrigger ControlID="Button1" />
25 </Triggers>
26 </asp:UpdatePanel>
27 </div>
28 </form>
29</body>
30</html>

Default2.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12public partialclass Default2 : System.Web.UI.Page
13{
14protected void Page_Load(object sender, EventArgs e)
15 {
16
17 }
18protected void Button1_Click(object sender, EventArgs e)
19 {
20 Control ctl = LoadControl("~/UserControlDemo.ascx");//loads into the page
21 ctl.ID ="UC1";
22this.ContentPlaceHolder.Controls.Add(ctl);//adds to page control tree (or at least it should)
23 }
24}

I knowI can use the "visible" property of my controls to toggle them on andoff a page to create a flicker free experience, however, my applicationis a database intensive app and I don't want the page running queriesagainst the database unless I'm absolutely sure the user wants them.Rendering a 10 forms and keeping them hidden isn't a big deal, butrunning 10 queries that the user never wants to see is, otherwise I'dstick to that method, its works perfectly. Any suggestions? Or requestsfor clarification? Any help you can provide is muchappreciated...thanks, Chris.

My suggestion is to not use an updatepanel for this. Google for ScottGu's blog on templating tricks; you can use a service to grab an ascx, feed it a datasource to populate the data then send the results to the page. use javascript to insert those results into the page DOM where needed, and code all your functionality in js or web methods of one form or another. It's a much cleaner / lower overhead way to do what you're trying to do anyway.


Hi Paul, I took a look at ScottGu blog, I believe this is the article you were referencing: 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

Unfortunately this is not the solution I am looking for. By using this method I lose the main benefits of ASP.net: managed code, event based triggers, and the rest of the integrated features. I believe this method will cause the same problem, whatever I load into the page, the page won't be aware of it and no events will fire.

For now I am going to have to use postbacks, and I'll used the update panels for keeping things like sorting gridviews postback-less.

Thanks for the suggestion though!


I am having exactly the same problem

Can someone please help?

In similar situations before, I have used javascript and other hacks, but I feel reluctant to try to do it again. If we have a framework that can be used and can make work simpler, then It makes sense.

However, these kind of problems are frustrating, and I don't know what is the resolution. I am sure people mus thave encountered this before.

Can someone help?


This is more a dynamic controls problem than an AJAX problem.

When you dynamically add a control, you have to add it EVERY request. By moving it from PageLoad to Button_Click, you've stopped creating the control every request. You only create it if the button is pressed. That is why the events won't fire when you use controls within the user control -- because on the postback, the control doesn't even exist! The postback data is for a control that isn't in the control tree, because you didn't add it, because the event that adds it isn't firing again.

The technique to solve this is to utilize viewstate to remember that the control has been added, so that you can add it from the LoadViewState method. In your click handler, call a new method - LoadUserControl(). Define LoadUserControl to create and add the control, and to set a viewstate key, ViewState["LoadUserControl"] = true. Then override LoadViewState, and after calling base.LoadViewState, look for that viewstate key. If its true, call LoadUserControl().

New problem... Now its possible it will be added twice -- if you click the same button a 2nd time, LoadViewState will call it, and so will your button click handler. So add code to your button click handler to avoid creating it if its already loaded -- just check for the viewstate key.


Infinities...This is very interesting, thank you for your response! Unfortunately you lose me when you talk about overriding the LoadViewState. How would you modify the following code to accomplish what you are saying?

protected void Button_Click(object sender, EventArgs e)
{
Control ctl = LoadControl("~/userControl.ascx");
this.Panel1.Controls.Add(ctl);
}
Thanks!

Ok, that sounds promising. But, I don't think the situation would work still.

I have a gridView. In every row of a gridview, one of the cells contains a nested update panel. When the user clicks on a particular row, a user control dynamically gets added to the nested update panel. This works fine.

When I click on a particular button INSIDE this user control then the postback disappears, no events are triggered and nothing happens. The fact that the control probably does not exist makes sense because it justifies what happens, as in no events are fired.

However now this user control has values and data inside it, so when you are saying to load that control again, what happens to the value and the data, it looks like that data is lost. Is that not right?

Basically, in my situation AJAX cannot help. In the first place my user control should already have a viewstate in order to persist the value of data and state of the elements inside the user control. Since its viewstate is not stored, the "re-adding" will simply not work at all.


gsinha25:

However now this user control has values and data inside it, so when you are saying to load that control again, what happens to the value and the data, it looks like that data is lost. Is that not right?

No that is not right. The fact you are loading it again doesn't mean its data is lost. All controls are reloaded every request, even the statically declared ones. ViewState maintains itself through the framework, but it only maintains the data in the control, not the control itself.

gsinha25:

Basically, in my situation AJAX cannot help.

You would have the same problem if you were not using ajax. What you'd see is that the loaded user control would disappear after you click a button in it.

gsinha25:

In the first place my user control should already have a viewstate in order to persist the value of data and state of the elements inside the user control. Since its viewstate is not stored, the "re-adding" will simply not work at all.

ViewState is maintained for the control. All you have to do is make sure it exists every request. It will work, trust me.


I'm sure the formatting of this is going to be off, but here's the basic idea.

protected void Button_Click(object sender, EventArgs e)
{
LoadUserControl();
}
private void LoadUserControl()
{
Control ctl = LoadControl("~/userControl.ascx");
this.Panel1.Controls.Clear();
this.Panel1.Controls.Add(ctl);

 ViewState["Loaded"] = true;

}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);

 if (ViewState["Loaded"] != null)
LoadUserControl();
 }


Hi Infinities,

This is starting to make sense. I believe what you are talking about will work for my problem - in fact I often assumed it had something to do with the viewstate, however my knowledge and experience with it is limited. (I am new to C# and ASP.net, coming over from ColdFusion.) I am still a little confused on the the LoadViewState override. As I understand it, this event fires after the Init event in the lifecyle, and it's goal is to reload the user control if it has been added to the page. One question that pops up here, and may be what gsinha was referencing, does chages to the control also progress if it is reloading the control every time? For instance, if the user control is a gridview populated from a database and I have sorted and/or filtered it, would these sorts and filters be passed along as well?

Another question, when you assign the view state key in "ViewState[" "] = true" does it matter which key you use? And a final question, where is the savedState object coming from in the LoadViewState override?

Thanks again for your help!

P.S. I read your writeup at your website on the viewstate, I think i'll need to read it three or four more times before I can make sense of it all but amazing stuff, I love the attention to detail!


ChrisCicc:

As I understand it, this event fires after the Init event in the lifecyle, and it's goal is to reload the user control if it has been added to the page.

The general role of LoadViewState is to deserialize the control's share of the page's entire viewstate payload. Think of viewstate as just a bunch of data -- data which is associated with each control on the page. On a postback, that data is available to the control that owns it again, if it's still around that is. The role of the code I gave you is to recreate the control if it was remembered previously that it had been created.

ChrisCicc:

One question that pops up here, and may be what gsinha was referencing, does chages to the control also progress if it is reloading the control every time? For instance, if the user control is a gridview populated from a database and I have sorted and/or filtered it, would these sorts and filters be passed along as well?

Yes -- because what you have to understand is that all controls are reloaded every request. In fact, the page is completely reconstructed from the ground up every request. Remember request/response mechanism of the web is essentially a stateless process. ASP.NET and other frameworks create the feeling of statefulness through tricks like ViewState and Session state. ViewState is persisted across posts -- the controls are not. You create the control tree for the page by either statically declaring it with asp.net markup, or by dynamically creating the controls yourself. But either way, the controls start completely fresh and new every request. ViewState is then deserialized and injected into the controls, restoring them to the state they were on the last request.

ChrisCicc:

Another question, when you assign the view state key in "ViewState[" "] = true" does it matter which key you use?

No -- the idea is just to remember the fact that the control was loaded. Each control's viewstate is scoped to it, so there's no risk of using a key thats already in use by some other control.

ChrisCicc:

And a final question, where is the savedState object coming from in the LoadViewState override?

That is the deserialized viewstate associated with that specific control. The base implementation uses it to repopulate the keys stored in the ViewState statebag.


ChrisCicc:

P.S. I read your writeup at your website on the viewstate, I think i'll need to read it three or four more times before I can make sense of it all but amazing stuff, I love the attention to detail!

Thanks for reading :) I know it's quite long... but hopefully worth it.


It works!! Thanks a bundle! This solved the most important problem I had, which was loading the user control on to the page via an Update Panel. It does however bring up a few further questions that I was hoping you could help with!

First, how do I modify your code so that I can have multiple buttons load different UCs each while still using the LoadViewState override? The following code is my best attempt at it:

Instead of using the click event to call the LoadUserControl function, I did this:

  
protected void LinkButton_Click(object sender, EventArgs e)
{
MainBodyPanel.Controls.Clear();
Control ctl = LoadControl("UserControl.ascx");
MainBodyPanel.Controls.Add(ctl);

ViewState["Loaded"] =true;
}

And then in the override I did as you suggested, only added an addtional If statement for each button and control,
and sent it back to the click event function instead of the LoadUserControl so that each control could have its
own viewstate key.
While I can add new controls to the page, I cannot see them again once another control calls the .clear()
function an all that is left is the viewstate which then throws an error as it doesn't see the same control tree.
Is there a better way?
 
The second problem I have is I cannot get different user controls to communicate with each other. This is
apparent in two places. The first is I have a user control with a set of links. it is these links that call the
other user controls into the update panel dynamically. If I add the UserControl dynamically before the page
loads, the links can't see the container panel on the page. I tried using this.findControl("...").Controls.Add()
but that didn't work. So for now I have the links hard coded into the page instead being their own user control,
but it's really too complex to keep doing it that way, and it limits my nesting options.
Thanks again for any help u can provide! 
 

Ok... help me understand :) You have a bunch of links, which when one is clicked, you want to dynamically load a user control into a particular spot. Is that 'spot' different for each link? If you click on one link and then another are there supposed to now be 2 controls on the page or does the 2nd one replace the first?

I'll assume you want only 1 control at a time.

What you described sounds like it should work. I personally wouldn't explicitly call the event handler -- thats usually a bad idea. It won't cause any problems if you know what you're doing but its better design to have a 3rd method that they both call, which gives each method a clear distinct purpose (its generally bad if you have to think... who called this method?).

One think you should definitely do is give the User Control you load a particular ID. Make the ID based on something that will (1) be exactly the same every time and (2) be different for different user controls. So for example, clicking on Link1 might load UC1.ascx with ID "uc1", and clicking Link2 might load UC2.ascx with ID "uc2". The reason for this is.. well, when you dont specify an ID, any control that requires one (textboxes for example) will use an autogenerated one. But if you load controls differently on a postback than you did on the first request, the IDs wont necessarily be the same, causing problems. Assigning an ID avoids that. You shouldn't have been getting the exception you mentioned... try what I said and let me know. If you still get it, show me some code...

About your user control communication problem... I'm not following 100%. Where and when exactly are you calling FindControl, and what control are you trying to find? With controls whenever you find yourself trying to get two of them to talk directly to each other... well its usually a sign that you could improve your design a bit. The control should be self sufficient, it shouldn't be broken because something else on the page isnt just so. Rather than have the control talk to the other control, you can have it raise an event. The page then listens for the event and decides what to do with it (something which the original control doesn't much care about), which may be to push something into another control on the page (the origin of which that control doesn't much care about). Much less coupled that way.


"I'll assume you want only 1 control at a time." correct assumption. there is a panel placeholder that the controls get swapped in and out of.

I tried adding the ID as you suggested but the exception still came up. Here is the code as it currently stands:

1protected void ViewCustomerListLinkButton_Click(object sender, EventArgs e)2 {3 MainBodyPanel.Controls.Clear();4 Control ctl = LoadControl("~/UserControls/CustomersControls/CustomerList.ascx");5 ctl.ID ="CustList";6 MainBodyPanel.Controls.Add(ctl);78 ViewState["CustList"] =true;9 }1011protected void AddCustomerLinkButton_Click(object sender, EventArgs e)12 {13 MainBodyPanel.Controls.Clear();14 Control ctl = LoadControl("~/UserControls/CustomersControls/CustomerAdd.ascx");15 ctl.ID ="CustAdd";16 MainBodyPanel.Controls.Add(ctl);1718 ViewState["CustAdd"] =true;19 }2021protected override void LoadViewState(object savedState)22 {23base.LoadViewState(savedState);2425if (ViewState["CustList"] !=null)26 ViewCustomerListLinkButton_Click(null,null);2728if (ViewState["CustAdd"] !=null)29 ViewCustomerListLinkButton_Click(null,null);3031 }

The exception is thrown because when I click on a second link, it Clears the MainBodyPanel control list, and the viewstate is looking for the control list that includes the now removed control. I tried various ways I could think of to remove the viewstate but to no avail...

"What you described sounds like it should work. I personally wouldn'texplicitly call the event handler -- thats usually a bad idea. It won'tcause any problems if you know what you're doing but its better designto have a 3rd method that they both call, which gives each method aclear distinct purpose (its generally bad if you have to think... whocalled this method?)."

I couldn't figure out a way to do this. I was having each click event pass the url via the function call LoadUserControl("~/control.ascx") but I couldn't figure out how to have the loadviewstate override pass the url back when needed, so I did it as you see above.

About the communication problem, in more detail, the problem is actually with the code above. Right now that is in my pages code behind, if i make those links into a user control, and then add the control to the page with those functions in the controls code behind, it cannot see the container panel (which in this case is the MainBodyPanel). I tried using the find control method but it still couldn't see it. With the links and event handlers hard coded it works fine.

Thanks!


With this code, once you click on one of the buttons, that control will always be loaded. When you click on one button you need to 'clear' the viewstate key of the other, otherwise you'll be trying to load both controls all the time. Pretty sure that is why you are getting the error, too. Easier if you just use the same key with a different value.

About the event handler thing...

protected void Link1_Handler(object sender, EventArgs args) { Foo(); }
private void Foo() { /* load Foo, set ViewState["Loaded"] = 1 */ };

protected void Link2_Handler(object sender, EventArgs args) { Bar(); }
private void Bar() { /* load Bar, set ViewState["Loaded"] = 2 */ };

protected override void LoadViewState(object savedState) {
base.LoadViewState(savedState);

if(ViewState["Loaded"] == 1) {
Foo();
}
else if(ViewState["Loaded"] == 2) {
Bar();
}
}

You might be tempted to store the path to the actual UserControl in ViewState, that way you can just LoadControl(ViewState["Loaded"]) ... but, don't :) Treat ViewState like user input. Don't trust it. If you did it that way, the user could maniuplate viewstate in such a way that they could cause any user control in your site to load, rather than be restricted to the two you want.

Ok... so I'm still confused about your links problem. You have each link as a user control, and when clicked you want them to load their content into the parent? Controls should not modify their parent's controls. It would be better like I said, to have an event raised by the control. The page, which contains all these link controls, just hooks that event on each control and then loads the control into the appropriate place. Your FindControl probably isn't working because FindControl only finds controls within the current naming container. User controls are naming containers. So when you say, this.FindControl("foo") from within a UserControl, you're only looking for a control named "foo" WITHIN the user control, not higher. To go higher you have to call FindControl on a control thats higher. But you still have to be careful with naming containers. You could start at the page level with this.Page.FindControl("foo"), but that will only find controls named "foo" that are children of page or children of non-naming containers in page. Imagine if you had a user control that contained control with ID "foo", and then you put 5 of them on the page. Which would you expect Page.FindControl("foo") to find? Its ambiguous -- thats why it won't find ANY. Each Foo is within a naming container, so their actual IDs are "uc1$foo", "uc2$foo", etc (where uc1=id of user control 1). If you know for sure the control will be in a particular place (for you it sounds like in a master page), then go ahead and hard code that ID... but be warned, its a fragile way to do it. Another approach is to have your Page expose a "MasterContainer" property of type Control. The user controls can then just say ((MyPageType)this.Page).MasterContainer.Controls.Add(), and it will work so long as the control is on a page that inherits from "MyPage" (which, all of your pages could inherit from).Ad infinitum... lots of different ways to deal with it.

Programmatically Adding Controls and Events

Hi, I am trying to add several link buttons to a page programmatically with the following code:

int i;
int i;
for (i = 0; i < 60; i++)
{
LinkButton lnk = new LinkButton();
lnk.ID = "region" + i;
lnk.CssClass = "mystyle";
lnk.Click += new System.EventHandler(lnk_Click);

addContent.Controls.Add(lnk);

}


which adds them perfectly, however I also want to add an event handler to them all (the same event handler) which I had hoped to achieve by adding the ' lnk.Click += new System.EventHandler(lnk_Click);'
however when the link buttons are now clicked the page freezes, any suggestions?

All that is assigned on the onclick event is a write out to a label within an ajax.net update panel.

Any help would be appreciated, cheers Jon

I set this up in my dev environment and wa sunabel to duplictae it. Can you post more of your code... the ASP and the code behind to give us a better idea of whats going on.

I got the code working - for some reason the fact that the linkbuttons were placed inside a updatepanel and that the 'childrenastriggers' set to true seems to cause the slow down.

I think i know the problem but i am not sure how to solve it!

basically my onload function generates around 1500 linkbuttons in tiny squares within an update panel, each assigned a unique ID.

onclick of each button it posts its unique number to a textbox (temporarily so i can see if it is doing something) it takes around 60 seconds to do this when the 'childrenastriggers' is set to true.

When this is not set to true it performs it instantly, which is fine, however what I am trying to achieve that on click of the linkbutton it puts the number in the box, and changes the css of the linkbutton, updates so the user can see it has changed.

However the update panel is refreshing the generation of 1500 link buttons - which is causing the slow down.

Without the update panel refreshing, and if i cause a full postback the change is instant.

Any ideas on how to get around this but still achieve something similar.


Try and place your button generation code in the Page_Init event.


worked a treat, thank you!

Programmatically adding hoverbehavior

I'm trying to convert some declarative code to its programmatic equivalent. I have the following. Am I missing something?

<control targetElement="objectElement">
<behaviors>
<hoverBehavior unhoverDelay="500" hoverElement="popup">
<hover>
<setProperty target="popupBehavior" property="PositioningMode" value="Absolute" />
<setProperty target="popupBehavior" property="x" value="50" />
<setProperty target="popupBehavior" property="y" value="50" />
<invokeMethod target="popupBehavior" method="show" />
</hover>
<unhover>
<invokeMethod target="popupBehavior" method="hide" />
</unhover>
</hoverBehavior>
</behaviors>
</control>

// <control targetElement="objectElement">
var objectControl =new Web.UI.Control(objectElement);
objectControl.initialize();
var objectControlBehaviors = objectControl.get_behaviors();

// <hoverBehavior unhoverDelay="500" hoverElement="popup">
var hoverBehavior =new Web.UI.HoverBehavior();
hoverBehavior.set_unhoverDelay(500);
hoverBehavior.set_hoverElement(popup);
objectControlBehaviors.add(hoverBehavior);

// <setProperty target="popupBehavior" property="PositioningMode" value="Absolute" />
var action =new Web.SetPropertyAction();
action.set_target(popupBehavior);
action.set_property("PositioningMode");
action.set_value("Absolute");
hoverBehavior.hover.addAction(action);

// <setProperty target="popupBehavior" property="x" value="50" />
var action1 =new Web.SetPropertyAction();
action1.set_target(popupBehavior);
action1.set_property("x");
action1.set_value("50");
hoverBehavior.hover.addAction(action1);

// <setProperty target="popupBehavior" property="y" value="50" />
var action2 =new Web.SetPropertyAction();
action2.set_target(popupBehavior);
action2.set_property("y");
action2.set_value("50");
hoverBehavior.hover.addAction(action2);

// <invokeMethod target="popupBehavior" method="show" />
var action3 =new Web.InvokeMethodAction();
action3.set_target(popupBehavior);
action3.set_method("show");
hoverBehavior.hover.addAction(action3);

// <unhover>
var unhoverBehavior =new Web.UI.HoverBehavior();
objectControlBehaviors.add(unhoverBehavior);

// <invokeMethod target="popupBehavior" method="hide" />
var action4 =new Web.InvokeMethodAction();
action4.set_target(popupBehavior);
action4.set_method("hide");
unhoverBehavior.unhover.addAction(action4);

Any help appreciated...

Hi,

it seems that you missed to call the initialize() method of the HoverBehavior.

You are missing the "popupBehavior" target, which needs to be attached, with the "id" set to "popupBehavior" to the <behaviors> tag under the <control> reference that you want to "pop up." For example, if you are wanting the "objectElement" to pop up, you would change that control reference in the following way:

<control targetElement="objectElement">
<behaviors>
<popupBehavior id="popupBehavior" ..the rest of the properties... />
</behaviors>
</control>


I was desperately looking on how to do this... and finally, I found the way... you got me started, so this is how to do it:

var test = document.getElementById("test");var p = document.getElementById("p");var popup =new Sys.UI.Control( p );

popup.initialize();

var objectControl =new Sys.UI.HyperLink(test);

objectControl.initialize();

var objectControlBehaviors = objectControl.get_behaviors();var pb =new Sys.UI.PopupBehavior();

pb.setOwner( popup );

pb.set_parentElement( objectControl );

pb.set_positioningMode(

"TopRight" );var invoke =new Sys.InvokeMethodAction();

invoke.set_target(pb);

invoke.set_method(

"show");var invokeu =new Sys.InvokeMethodAction();

invokeu.set_target(pb);

invokeu.set_method(

"hide");var behavior =new Sys.UI.HoverBehavior();

behavior.setOwner( objectControl );

behavior.initialize();

behavior.hover.addAction( invoke );

behavior.unhover.addAction( invokeu );

objectControlBehaviors.add( behavior );


And actually, here is the final version:

function

setHover( link, domPopup )

{

var popup =new Sys.UI.Control( domPopup );

popup.initialize();

var objectControl =new Sys.UI.HyperLink( link );

objectControl.initialize();

controls[index] = objectControl;

index++;

var objectControlBehaviors = objectControl.get_behaviors();var pb =new Sys.UI.PopupBehavior();

pb.setOwner( popup );

pb.set_parentElement( link );

pb.set_positioningMode( Sys.UI.PositioningMode.Absolute );

pb.set_x( 45 );

pb.set_y( 0 );

var invoke =new Sys.InvokeMethodAction();

invoke.set_target(pb);

invoke.set_method(

"show");var invokeu =new Sys.InvokeMethodAction();

invokeu.set_target(pb);

invokeu.set_method(

"hide");var behavior =new Sys.UI.HoverBehavior();

behavior.setOwner( objectControl );

behavior.set_hoverElement( domPopup );

behavior.initialize();

behavior.hover.addAction( invoke );

behavior.hover.add( populatePanel );

behavior.unhover.addAction( invokeu );

objectControlBehaviors.add( behavior );

}

Additional notes:

The popup div has to specific position:absolute. This might be a bug since you do not have to do that with the declarative syntax.

If you are dynamically creating and destroying these, make sure to do something like:

function

destroy()

{

for(var i = 0; i < index; i++ )

{

var b = controls[i].get_behaviors();

b =

null;

}

index = 0;

}

(I'm sure the right thing is to destroy the objects, but this works for my demo in an hour)

Hope this helps...


I'm getting closer whoever started this I'm trying very hard to make danz stuff work.


I'm getting closer whoever started this I'm trying very hard to make danz stuff work. First post was better Danz


Here you go, tested on firefox and ie6:

function CreateHoverOptions(popup_id, parentid, behaviorid, delayMS)
{
var popup_element = getObj(popup_id);
var popup_control = new Sys.UI.Control($(popup_id));
var parent = new Sys.UI.Control($(parentid));
var PopOptions = new Sys.UI.PopupBehavior();

PopOptions.set_id(behaviorid);
PopOptions.set_parentElement(getObj(parentid));
PopOptions.set_positioningMode("TopLeft");
popup_control.get_behaviors().add(PopOptions);

var HoverOptions = new Sys.UI.HoverBehavior();
HoverOptions.set_unhoverDelay(delayMS);
HoverOptions.set_hoverElement(popup_element);
parent.get_behaviors().add(HoverOptions);

var hoverAction = new Sys.InvokeMethodAction();
hoverAction.set_target(PopOptions);
hoverAction.set_method("show");
HoverOptions.hover.addAction(hoverAction);

var unhoverAction = new Sys.InvokeMethodAction();
unhoverAction.set_target(PopOptions);
unhoverAction.set_method("hide");
HoverOptions.unhover.addAction(unhoverAction);

PopOptions.initialize();
HoverOptions.initialize();
popup_control.initialize();
parent.initialize();
}

HOW to USE:
1. call following method in pageLoad()
CreateHoverOptions("OPTIONS", "image4", "beh", 1000);

HTML:
<div>
<img id="image4" src="http://pics.10026.com/?src=../images/tlogo.gif" />
</div>

<div id="OPTIONS" style="visibility:hidden;display:none;">
<div style="background-color:Yellow;">
<a href="http://links.10026.com/?link=javascript: alert('delete this pic');">[x]</a>
<a href="http://links.10026.com/?link=#">[e]</a>
</div>
</div

Has anyone updated the above code to the latest Ajax beta 1 or beta 2 version??

Thanks, Greg Benoit

Programmatically adding multi DragPanelExtenders?

Hi;

First of all what I need is to have more then one dragable panels inside my page. DragAndDrop em, record their locations to the DB

I'm using this script that I found in asp.net forum to find the location:

<scripttype="text/javascript">
Sys.Application.add_load(dragSetup);
function dragSetup() {
var dragPanel = $find('dragPanelBehavior1');
dragPanel.add_propertyChanged(locationUpdatedHandler);// the handler would get the name of the property from the event args and if it is 'location' then do the right thing.
returnfalse; }

function locationUpdatedHandler(sender, eventargs) {
if(eventargs.get_propertyName() =='location') {
var dragPanel = $find('dragPanelBehavior1');
var label = $get('dragPanelLocation');
var loc = dragPanel.get_location()
label.innerHTML = loc;}
}
</script>

However because of this script I have in the webusercontrol whenever I add my second webusercontrol it returns an error because they both aims the same panel's dragPanelBehavior1.

I couldn't solve this problem, any help would be preciated.

Again what I actually need is more then one dragable panels containig a webusercontrol and that I can find the location.

Thanks in advance

Hi Kaan,

First, DragPanelExtender's BehavirID should be uniquej though they are in different WebUserControls which are located in the same page.

Secondly, in your situation, I think you should remove out the Sys.Application.add_load(dragSetup) and its related functions from WebUserControls to the page.

To get or set the Panel's location , we can also use

//get

var el = $find('DragPanelBID').get_element();
var newLocation = $common.getLocation(el);

//set

var finalLocation = new Sys.UI.Point(x,y);
$find('DragPanelBID').set_location(finalLocation);

Hope this help.

Best regards,

Jonathan

Programmatically Creating TabContainer and Adding Tabs

Plan - create a TabContainer via codebehind. Then read from a SQL DB (in this case NorthWind) and use the each CategoryName as a TabPanel.

Problem - Nothing displays. However, when I place TabContainer and TabPanel controls on the page during design, then run the code, I get the tabs with Category Names, but the first tab is the default name of the one I placed on the page during design.

Thoughts/suggestions?

Forgot to add the code (DUH):

Imports AjaxControlToolkit
Imports System.Data.SqlClient
Imports System.Configuration
Partial Class _Default
Inherits System.Web.UI.Page

Dim connectionString As String = "Data Source=MATT\SQLExpress;Initial Catalog=LucaSQL;Integrated Security=True;"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not Page.IsPostBack) Then
ReadCategories(connectionString)

End If
End Sub

Private Sub ReadCategories(ByVal connectionString As String)
Dim queryString As String = _
"SELECT CategoryID, CategoryName FROM dbo.Categories"

Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()

Dim reader As SqlDataReader = command.ExecuteReader()
'Dim tc As New TabContainer

' Call Read before accessing data.
While reader.Read()
Dim CategoryName As String = reader("CategoryName")
Dim tab As New TabPanel
tab.HeaderText = CategoryName
tc.Tabs.Add(tab)

End While

' Call Close when done reading.
reader.Close()
End Using
End Sub
End Class


Hi,

In this case, you need to change its visibility with javascript. For example:

<%@. 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_Load(object sender, EventArgs e)
{
for (int i = 0; i < 3; i++)
{
TabPanel tp = new TabPanel();
tp.HeaderText = "tp" + i.ToString();
tp.Controls.Add(new TextBox());
TabContainer1.Tabs.Add(tp);
}
}
</script
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function pageLoad()
{
$get("TabContainer1").style.visibility = "visible";
}
</script>

</head>
<body>
<form id="form1" runat="server">
<asp:scriptmanager ID="Scriptmanager1" runat="server"></asp:scriptmanager>
<div>
<ajaxToolkit:TabContainer ID="TabContainer1" runat="server">
</ajaxToolkit:TabContainer>
<br />
<br />
<br />
<br />
</div>
</form
</body>
</html>

Saturday, March 24, 2012

Question about adding data to a databse (Im new to Atlas)

I'm wondering how I use Atlas to dynamically add data to a database using the default.aspx.cs file and not a web service. Any help is appreciated.

hello.

well, you have 2 options (one sucks more that the other :D):

1. use page method

2. use an updatepanel.