Showing posts with label programatically. Show all posts
Showing posts with label programatically. Show all posts

Wednesday, March 28, 2012

Programatically accessing Panels and Triggers (In CodeBehind at least)

I have a extensive toolkit that I have written over the past year or two that automatically generates all of my grids, dropdowns, "detail views" and other things. I wanted to start incorporating some snazzy ajax enabled inline calendars and stuff like that. However all of my code is buried deep within class files that generate the controls dynamically. A typical page that has a grid in it is simply a ASP:Placeholder tag, and a snip of codebehind saying what table the user wants to view, and the users group ID (around 3 lines of actual code).

I so to really AJAX enable this I would need a few things to work out, but I don't want to bore you all with those details. I would have tried to do it all of this in my class library already if I could, but when I instantiate a new Trigger, and type "t." to see what options I have, they are only the 4 options that I would have with an variable of type object (Equals, ToString, etc). I cannot even find the "EnablePartialRendering" flag that you need to setup on these panels on the updatepanel obj. Many of these controls have very few if any extra methods/properties/events different from the "System.Web.UI.Control" that they all inherit from.

Am I doing something wrong?

AB

hello.

is this an intellisense problem? if so, have you added the using directive to the source file?


I don't think that there is a problem with the intellisense, I mean, I have been coding for a few years now in .Net, using the intellisense to figure out how things work, without even really bothering with the documentation. It would seem that the Atlas is not to the point where it has the necessary XML markups to the source for the descriptions and what nots to kick in...

Basically, I am looking for examples, given an ASP.Net placeholder, to atlas enable it from the codebehind only, not from the designer... Make sense?

AB

hello again.

let me see if i got this correctly: you want to use the atlas server controls (ex.: UpdatePanel) from your source code files, right?

well, this should work, though i think that the intellisense info is not done yet (ie, you can see the methods/properties, but no info about them). so, your best option is to use .net reflector to see what it does (or, you can allways post your doubts here)


Yes, that is correct.

Have you seen any examples accessing the UpdatePanel from source code? The only examples I have found are in the ASPX Markup files, not the .ASPX.CS codebehind files...

The methods and properties I see are very limited, but as I see it, it would be done like:

Microsoft.Web.UI.ControlEventTrigger t = new Microsoft.Web.UI.ControlEventTrigger();
Microsoft.Web.UI.UpdatePanel up = new Microsoft.Web.UI.UpdatePanel();
up.Controls.Add(SomeLiteralControl);
t.ControlID(SomeButtonControl.ID);
t.EventName("Click");

Now, I can cause "SomeButtonControl" 's click event to change the Literals content and it will ajax that new content into the page?

AB
Ohh yeah, I also don't get the autocomplete for <atlas:UpdatePanel in my ASPX pages, any ideas on that?

AB

hello.

yep, adding triggers should be done like that ( though you still need to add the trigger to the collection maintained by the panel and this should be done until the init event of the page - btw, adding controls to the panel can't be done like that because you need a template).

what problems are you having with the updatepanel?


Hello,

I think I have the same problem. I thought I will start and try to change the example from

http://atlas.asp.net/docs/util/srcview.aspx?path=~/Server/samples/UpdatePanel.src

So the Panel2 is added to PlaceHolder on Page, but the panel doesn't update than.

Any ideas how it should be then, were to initiate the Panel.

For the moment my source code looks like that:

public

partialclassDefault6 : System.Web.UI.Page

{

privateUpdatePanel Panel2;protectedint PostBackCount

{

get

{

return (int)(ViewState["PostBackCount"] ?? 0);

}

set

{

ViewState[

"PostBackCount"] =value;

}

}

protectedoverridevoid OnInit(EventArgs e)

{

this.Init +=new System.EventHandler(this.Page_Init);this.Load +=new System.EventHandler(this.Page_Load);base.OnInit(e);

}

publicvoid Page_Init(Object sender,EventArgs e)

{

Panel2 =

newUpdatePanel();

Panel2.Mode =

UpdatePanelMode.Conditional;

Panel2.ID =

"UPForm";

Panel2.ContentTemplate =

newCTemplate(this);ControlEventTrigger pBtnClikEventTrigger =newControlEventTrigger();

pBtnClikEventTrigger.ControlID =

"Panel3bButton";

pBtnClikEventTrigger.EventName =

"Click";

Panel2.Triggers.Add(pBtnClikEventTrigger);

phPanel2.Controls.Add(Panel2);

}

protectedvoid Page_Load(object sender,EventArgs e)

{

if (IsPostBack)

{

PostBackCount++;

}

}

protectedvoid Panel3aButton_Click(object sender,EventArgs e)

{

Panel2.Update();

}

publicclassCTemplate :ITemplate

{

privateDefault6 m_pInnerControl;public CTemplate(Default6 pInnerControl)

{

m_pInnerControl = pInnerControl;

}

publicvoid InstantiateIn(System.Web.UI.Control container)

{

container.Controls.Add(

newLiteralControl(" [" + m_pInnerControl.PostBackCount +"] "));

}

}

}

thanks a lot in advance

Anna


hello again.

sorry, i didn't look with attention to your code. btw, don't add the panel like that...OnInit is called ot handle the init event, so just call method that adds the panel instead of creating a delegate...i see that you set the trigger to a panel3dbutton...where is this button placed? note that if's inside an user control, you can't do that because you need the full id of the control.


hi,

Thanks for sam clues.

But i noticed that the posted code

upadtes the panel. I changed the line

container.Controls.Add(newLiteralControl(" [" + m_pInnerControl.PostBackCount +" " +DateTime.Now +"] "));

And the date is changed every button click. Only the m_pInnerControl.PostBackCount is always zero.

Anna

Programatically add UserControls that Contain an UpdatePanel

In the release notes for the latest release it states that you can programatically add UpdatePanels now. I have a user control (ascx) that contains an UpdatePanel and a Timer to refresh the panel. When I add more than one of these controls to the page programatically the first refresh of one of the UpdatePanels blanks out all of the data in all of ascx controls. When I add the controls to the page in the aspx code everything works fine. I need to add them programatically since the number of them is configurable. I have the ScriptManager control on the page with partial refresh enabled. Is there something special I need to do when I add these controls programatically?

UserControl

<%@dotnet.itags.org. Control Language="C#" AutoEventWireup="true" Codebehind="DataPart.ascx.cs" Inherits="MS.Support.KnowledgeManagement.VisualKb.DataPart"
EnableViewState="false" %>
<div class="dataPart">
<div id="divHeader" class="dataPartHeader" runat="server">
<img alt="Collapse" style='float: right' src='images/Collapse.gif' title='Collapse'
onclick="ExpandCollapse(this,this.parentElement.parentElement.children(1))" />
<asp:Label ID="lblHeader" runat="server"></asp:Label>
</div>
<div id="divBody" class="dataPartBody" runat="server">
<asp:UpdatePanel ID="divUpdate" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<vkb:VkbBulletedList ID="blItems" runat="server" BulletStyle='disc' DisplayMode='HyperLink'
CssClass="dataPartList" NewIndicatorFontColor="red">
</vkb:VkbBulletedList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="timerRefresh" />
</Triggers>
</asp:UpdatePanel>
<div style='text-align: center; width: 100%'>
<asp:HyperLink ID="lnkViewAll" runat="server" CssClass="dataPartLink">View All</asp:HyperLink>
</div>
</div>
</div>
<asp:XmlDataSource ID="xmlDataSource" runat="server" XPath="descendant::Items/Item"
EnableCaching="false" EnableViewState="False"></asp:XmlDataSource>
<asp:Timer ID="timerRefresh" OnTick="timerRefresh_Tick" runat="server">
</asp:Timer>

Code to add ascx to page

dp = Page.LoadControl("DataPart.ascx") as DataPart;
dp.DataType = "Article";
dp.HeaderColor = Color.LightGray;
dp.HeaderFontColor = Color.Black;
dp.HeaderText = nodes.Current.GetAttribute("Name", String.Empty);
dp.CategoryId = Convert.ToInt32(nodes.Current.GetAttribute("Id", String.Empty));
dp.BodyColor = Color.WhiteSmoke;
dp.EnableRefresh = false;
dp.XmlData = nodes.Current.SelectSingleNode("Items") != null ? nodes.Current.SelectSingleNode("Items").OuterXml : "<Items />";
td.Controls.Add(dp);

I tried a simple example just using a RadioButtonList against XML data source and everything seemed to work fine when adding dynamically. What's in the VkbBulletedList control?
Its just an override of the BulletedList control to add some custom text to each bulleted item.

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.

Programatically collapse a panel

With Beta 2, does anyone know how to programatically collapse a panel controlled by the CollapsiblePanel extender? When I click a button, I want to collapse a panel and change the ImageControl(image) to a different image...Here's another thread that addresses the same issue and has a code sample, although I don't know if it's right since it doesn't actually work for me.

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


I think this iswork item 5688.

this works for me

Me.CollapsiblePanelExtender1.ExpandControlID = "Panel3"

Me.CollapsiblePanelExtender1.Collapsed = False

Programatically Create Tab Container and Tab Panels

Hi,

How can I create a tab container and subsequent tab panels within it using C# in the code behind?

Any help would be much appreciated.

Hello,

You can you the PlaceHolder Control to add the TabContainer on the page, like so: make sure to add the reference at the top - using AjaxControlToolkit;

 TabContainer container =new TabContainer(); TabPanel panel1 =new TabPanel(); TabPanel panel2 =new TabPanel(); TextBox txtOne =new TextBox(); txtOne.ID ="txtOne"; txtOne.Text ="Example Text"; panel1.HeaderText ="This is Header 1 Text"; panel1.Controls.Add(txtOne); panel2.HeaderText =" This is Header 2 Text"; container.Tabs.Add(panel1); container.Tabs.Add(panel2); PlaceHolder1.Controls.Add(container);
 
Hope this helps. 

Yep that was perfect...thanks for this!

programatically disable dropdown in Ajax updatepanel

I've searched high and low for what seemed would be a simple and frequently used method to access the properties of a drop down contained in a Ajax UpdatePanel without finding anyone who seems to have needed to do this or who has solved it. Maybe Microsoft decided nobody would ever want to do such a weird thing!

I have users with various permission levels. Depending on their level, on page load I need to disable drop downs which are contained within Ajax Updatepanels.

I can expose the properties of the UpdatePanels themselves but they do not support the enable property, only invisible which is no help.

Anyone know how this is done ?

Thanks

Aren't you able to just set the Enabled property of the appropriate DropDownList's?


Dont depends only on UI elements enable/disable state. Also enusre the User level in server side. Can pls post some code i mean in which point you want to disable the dropdown list.

Use CascadingDropDown control in AJAXControlToolKit

http://www.asp.net/AJAX/AjaxControlToolkit/Samples/CascadingDropDown/CascadingDropDown.aspx


Hi,

Are you using the AJAX extension version 1.0.61025.0 ?

I'm using this one. The controls inside UpdatePanel can be accessed directly. For instance:

<%@. 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) { DropDownList1.Enabled = false; }</script><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:DropDownList ID="DropDownList1" runat="server"> </asp:DropDownList> </ContentTemplate> </asp:UpdatePanel> </div> </form></body></html>

Programatically Expand CollapsiblePanel (With Lastest ToolKit)

The issue I am experiencing is due to upgrading to the latest ToolKit. I previously was able to use this code on a postback to expand a collapsible panel.

Previous Code:
Dim clp2 As CollapsiblePanelProperties = CollapsiblePanelExtender2.GetTargetProperties(Panel2)
clp2.ClientState =True
clp2.Collapsed =False

However I do understand that with the upgrade the Properties sections under each of the ToolKit controls is no longer valid. I personally liked the ability to place multiple <atlasToolKit:Properties> tags underneath ONE <atlasToolKit:CollapsiblePanel> tag. Why did you remove that?? It was easy to migrate but a hassle in regards to having to set up a new tag for each time. Anyhow... off of the soapbox.

Current Code:
Dim clp2As CollapsiblePanelExtender = CollapsiblePanelExtender2
clp2.ClientState =True
clp2.Collapsed =False

This fails to expand the Panel on a postback. Any help or solutions?

JoeWeb

I believe the ClientState value needs to be lower cased and quoted as per this post:http://forums.asp.net/thread/1325048.aspx.


Yeah after playing around with it for a little bit... I actually discovered that the following code fixed it.

Dim clp2As CollapsiblePanelExtender = CollapsiblePanelExtender2
clp2.ClientState =False
clp2.Collapsed =False

All that is different is that I set both to false.

Anyhow I figured it out about a week ago sorry I didn't post an update. Thanks!

JoeWeb

Programatically hiding Tabs in TabContainer is not hiding the HeaderText

I wanted to hide/Show one of the TabPanel programatically.

so basically I am doing this.TabContainer.Tabs[1].Visible = false;

Even thought the body of that TabPanel is hiding , the Header Text is still visible without a Tab background.

Please let me know if anyone has found a solution if faced the same problem.

Thanks

Maybe have a look at how the sample does it with script in its ToggleHidden method? Or try the .Enabled property?

it's better to use multiview and view as tab, it's works without problem

this is the code:

MultiView1.ActiveViewIndex = 2

you don't have to hide or show, just send to multiview control the index of the view you want to acitvate.


Actually there is one very simple solution:

tab.visible = false;

tab.headertext=""

And this works perfectly for me.


I use tabPanel._hide() and tabPanel._show(); on the client side. Where tabPanel = $find('tabPanelClientID');

Can anyone tell me how to do the same AND compatible with server refresh of the page... ie. If my client javascript code alters which tabs are visible using _show() and _hide(), then a button to submit the form is pressed can the tab display propertied be maintained across refreshes? hope that makes sense... :)

Currently if I do that above then returned page is reset to the original tab settings.

My scenario is...

I have 4 tabs. as the user selects from various drops downs, tabpanel2 is either hidden or kept shown. the form is eventually submitted to the server and is refreshed, but the tabs are not as they had previosuly been set!!!

I was looking for some kind of proprty like ClientState...?

help


you can also use:

TabContainer1.Tabs(3).Enabled =

False

...then you don't have to hit both the visible and headertext. You also won't have to put the text back that way either.

Dan Ribar


I have a question related to the way you are using the client-side script to show/hide the tabs. I have a tab container (clientID = tcMain) and 4 tab panels (tp1, tp2, tp3, tp4). When I tried to use the following to hide a panel I'm getting a javascript error stating "null is null or not an object". How are you able to resolve the show/hide functions?

My code:

$find('tp2')._hide(); --> failed with the above error

$find('tcMain').get_tabs()[1]._hide(); --> failed with the same error as above

$find('tcMain_tp2')._hide(); --> failed

document.getElementById('tcMain_tp2').style.visibility = 'hidden'; --> failed, could not get visibility property

Can you send me your code?


From the online sample at http://ajax.asp.net/ajaxtoolkit/Tabs/Tabs.aspx:

function ToggleTab(enable, tabNumber) {
$find('<%=TabContainer1.ClientID%>').get_tabs()[tabNumber].set_enabled(enable);
}

hides or shows the tab

function EnableTab(tabNumber)
{
$find('<%=TabContainer1.ClientID%>').set_activeTabIndex(tabNumber);
}

enables the tab which unhides it

would do the trick.

Programatically set ImageUrl in ModalPopup

Hi I have a DataList that populates from an SQL datasource. One control in the DataList is an image whose ImageUrl i am currently setting as follows:

protected void dlItems_ItemDataBound(object sender, DataListItemEventArgs e)
{
Label lblItemID = (Label)e.Item.FindControl("lblItemID");
Image imgItem = (Image)e.Item.FindControl("imgItem");

imgItem.ImageUrl ="~/Images/Items/" + lblItemID.Text +".jpg";
}


I want to be able to click the image and get a modal popup which displays a large view of the image. I have wrapped the image (imgItem) in a LinkButton. Heres the code:

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<script runat="server">
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public void SetLargeImagePath(int contextKey)
{
imgLargeImage.ImageUrl = "~/Images/Items/" + contextKey.ToString() + ".jpg";
}
</script>
<div>
<asp:DataList ID="dlItems" runat="server" DataKeyField="pkiItemID" Width="100%" OnItemDataBound="dlItems_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lblItemID" runat="server" Text='<%# Eval("pkiItemID")%>' Visible="False" CssClass="ItemText"></asp:Label>
<asp:Label ID="bSpecialOfferLabel" runat="server" Text='<%# Eval("bSale")%>' Visible="False" CssClass="ItemText"></asp:Label>
<table width="100%" class="Table">
<tr>
<td rowspan="6" valign="top">
<asp:LinkButton ID="lnkImage" runat="server">
<asp:Image ID="imgItem" runat="server" Width="150px" AlternateText="Click for a larger view" />
</asp:LinkButton>
<cc1:ModalPopupExtender ID="ModalPopupExtender" runat="server" TargetControlID="lnkImage" PopupControlID="pnlLargeImage"
BackgroundCssClass="modalBackground"
OkControlID="OkButton" DynamicControlID="Label1" DynamicContextKey='<%# Eval("pkiItemID")%>' DynamicServiceMethod="SetLargeImagePath" >
</cc1:ModalPopupExtender>
</td>
<td style="width: 104px; padding-left: 5px;"><h2>Title:</h2></td>
<td><asp:Label ID="szTitleLabel" runat="server" Text='<%# Eval("szTitle")%>' CssClass="ItemText"></asp:Label></td>
<td style="width: 112px" rowspan="6" valign="middle">
</td>
</tr>
<tr>
<td style="width: 104px; padding-left: 5px;"><h2>Type:</h2></td>
<td><asp:Label ID="szItemTypeLabel" runat="server" Text='<%# Eval("szItemType")%>' CssClass="ItemText"></asp:Label></td>
</tr>
<tr>
<td style="width: 104px; padding-left: 5px;"><h2>Status:</h2></td>
<td><asp:Label ID="szItemStatusLabel" runat="server" Text='<%# Eval("szItemStatus")%>' CssClass="ItemText"></asp:Label></td>
</tr>
<tr>
<td style="width: 104px; padding-left: 5px;"><h2>Description:</h2></td>
<td><asp:Label ID="szDescriptionLabel" runat="server" Text='<%# Eval("szDescription")%>' CssClass="ItemText"></asp:Label></td>
</tr>
<tr>
<td style="width: 104px; padding-left: 5px;"><h2>Price:</h2></td>
<td><asp:Label ID="mPriceLabel" runat="server" Text='<%# String.Format("{0:c}", Eval("mPrice"))%>' CssClass="ItemText"></asp:Label></td>
</tr>
<tr>
<td style="width: 104px; padding-left: 5px;"><h2><asp:Label ID="mOfferPriceLabelStatic" runat="server" Text="Offer Price:"></asp:Label></h2></td>
<td><asp:Label ID="mOfferPriceLabel" runat="server" Text='<%# String.Format("{0:c}", Eval("mSalePrice"))%>' CssClass="ItemText"></asp:Label></td>
</tr>
<tr>
<td align="center" colspan="4">
<asp:Button ID="btnAddToBasket" runat="server" CssClass="Button" Text="Add To Basket" />
<asp:Button ID="btnBuyNow" runat="server" CssClass="Button" Text="Buy Now" /></td>
</tr>
</table>
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="dlItemsDataSource" runat="server" CancelSelectOnNullParameter="False" ConnectionString="<%$ ConnectionStrings:ConnectionString%>" SelectCommand="spREAD_tblItems" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="pkiItemID" Type="Int32" />
<asp:Parameter DefaultValue="BRACELET" Name="fkiItemTypeShortText" Type="String" />
<asp:Parameter DefaultValue="FORSALE" Name="fkiItemStatusShortText" Type="String" />
<asp:Parameter DefaultValue="True" Name="bPublic" Type="Boolean" />
<asp:Parameter Name="bSale" Type="Boolean" />
<asp:Parameter Name="mPrice" Type="Decimal" />
</SelectParameters>
</asp:SqlDataSource>
</div>
<asp:Panel ID="pnlLargeImage" runat="server" Width="50%">
<asp:Panel ID="pnlHeader" runat="server" Style="cursor: move;background-color:#DDDDDD;border:solid 1px Gray;color:Black" HorizontalAlign="Center" Width="100%">
<div>
<p>Larger view of item</p>
</div>
</asp:Panel>
<div>
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:Image ID="imgLargeImage" runat="server" Width="200px" />
<p style="text-align: center;">
<asp:Button ID="OkButton" runat="server" Text="OK" />
</p>
</div>
</asp:Panel>
</asp:Content>

This currently will load the ModalPopup and give Label1 the value of the pkiItemID, so i am successfully getting the item ID and passing it to the ModalPopup.

The problem is that the ImageURL is not being set. Oddly the SetLargeImagePath() method does not appear to run (breakpoints are ignored), although the Label1 value is being set??

Does anyone have any ideas how to get the image to appear in the ModalPopup?

Many thanks

Hi Assimalyst,

Assimalyst:

<script runat="server">
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public void SetLargeImagePath(int contextKey)
{
imgLargeImage.ImageUrl = "~/Images/Items/" + contextKey.ToString() + ".jpg";
}
</script>

Please contextKey should be a string type. For example, public void SetLargeImagePath(string contextKey){};

We suggest that you should use a debugging tool such as Web Development Helper or Fildder etc.

Assimalyst:

I want to be able to click the image and get a modal popup which displays a large view of the image.

Here is a sample which implement on the client side.

<%@. 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"></script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Change Picture</title> <style> .modalBackground { background-color:Gray; filter:alpha(opacity=70); opacity:0.7; } .modalPopup { background-color:#FFD9D5; border-width:3px; border-style:solid; border-color:Gray; padding:3px; width:250px; } </style></head><body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager><asp:Image ID="Image1" runat="server" ImageUrl="~/pic/upg_Business.jpg" imgUrl="../pic/upg_HomePremium.jpg" onclick="changePicture(event.srcElement.imgUrl)"/><asp:Image ID="Image2" runat="server" ImageUrl="~/pic/upg_HomeBasic.jpg" imgUrl="../pic/upg_Ultimate.jpg" onclick="changePicture(event.srcElement.imgUrl)"/> <asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" Height="200px" Width="300px" style="display:none"> <asp:Image ID="Image3" runat="server" ImageUrl="~/pic/AJAX.gif"/> <asp:Button ID="Button2" runat="server" Text="Cancel" /> </asp:Panel> <ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="Button1" PopupControlID="Panel1" CancelControlID="Button2"> </ajaxToolkit:ModalPopupExtender> <div style="display:none"> <asp:Button ID="Button1" runat="server" Text="Button" /> </div> <script type="text/javascript" language="javascript"> function changePicture(imgUrl){ $get("<%=Image3.ClientID%>").src = imgUrl; $get("<%=Button1.ClientID%>").click(); } </script> </div> </form></body></html>

I hope this help.

Best regards,

Jonathan

programatically updating a panel using onblur

Ok, this is driving me nuts and I can't believe there's not a way to do this.

Basically I have a user control that dynamically adds text boxes to its control tree at runtime. I have an UpdatePanel control sitting in the top of my user control with a button and a literal control. When the button is clicked it calls a buttonclicked method in the user control that sets the literal to some text and calls the update method on the panel. It all does what it's supposed to do when I click the button and AJAX works just fine.

Now here's the problem, how on Earth do I add an onblur event to the dynamically created text boxes that will either

a) update the panel; or

b) call the buttonclicked method directly; or

c) click the button

I've tried

1txtBox.Attributes.Add("onblur","javascript:__doPostBack('ctl00_contentPlaceHolder_quoteControl_quoteButton','OnClick','');");

And a large number of variations on the above but to no avail. The problem with the above is that I don't necessarily know the full id of the button control at compile time (and even if I did I really, REALLY wouldn't want to hard code it in my class) and if it doesn't find the control then it does a full form postback making the update panel redundant. I understand that I cannot wire in a custom event handler directly to the onblur method (like you can for the text changed) so it has to be client side.

Is there a way to trigger server side events through client side script? I have to get this done even if it involves hand rolling some javascript function that I can call from the onblur attribute to call the event.

I'm a back end business tier coder so any help with the client side would be most gratefully appreciated.

Rick Edwards

Ok, I've discovered a nasty way to do this using the event hi-jacking technique or "hidden button" method found here:

http://www.dotnetjohn.com/articles.aspx?articleid=224

I'd originally shy'd away from this as it's blatantly a hack but having now spent two day researching this I can't find another way of doing it.

Basically I add a hidden button to my update panel on the parent control and wire in the button click method on the parent control code behind. I then raise the event handler in the parent user control and pass this to the child control classes that are part of my control factory. When a textbox control is manufactured by the factory I can then add the oblur attribute and wire in the button click event handler. The button click method is initialised in the parent user control and within it I call the update method for the AJAX panel.

This is great for just updating a single panel from multiple onblur events, the problem now occurs if I want to update different panels from different textbox controls, I suddenly have to start adding hidden buttons all over the place so this is far from an ideal answer.

I've just found an article on asynchronous callback features in .NET2 and it looks like I might be able to roll my own textbox control with an onblur method built in, anyone with any experience of this?

Rick Edwards


Sorry if I'm missing something, but why couldn't you just set AutoPostBack="true" on the TextBox?

Firstly the autopostback event is fired on either tabbing out of the textbox or on pressing enter and not necessarily on loss of focus. Also I don't want to fire a postback event, I actually need to fire a custom event that calls the update method on my update panel and therefore run an asynchronous postback and a partial render. I don't want to rerender the entire form.

Hope that makes sense. I tried the autopostback initially thinking along your lines but it couldn't do what I wanted.

Rick Edwards


Yes, you would be limited to whenever AutoPostBack actually fires. But then it will do an async postback (as long as it's in your UpdatePanel or set as a trigger) and run whatever handler you've set in OnTextChanged. It shouldn't reload the entire page.

If AutoPostBack doesn't do what you want, your hidden button method should work, but I'd use MyButton.ClientID to get the ID so you don't have to hardcode it (which as you said is error-prone).

Monday, March 26, 2012

Programmatically setting ConfirmText of ConfirmButtonExtender

I was wondering if it's possible to set the ConfirmText of the CBE programatically at run-time?
I can't seem to access the ConfirmText property in my VB code.

ThanksYes, it is. The code looks something like:

<%@. Page Language="VB" %><%@. Register Assembly="AtlasControlToolkit" Namespace="AtlasControlToolkit" TagPrefix="atlasToolkit" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"> Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) CBE.TargetProperties(0).ConfirmText = "Here I am" End Sub</script><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> <atlas:ScriptManager ID="SM" runat="server"> </atlas:ScriptManager> <asp:Button ID="Button1" runat="server" Text="Button" /> <atlasToolkit:ConfirmButtonExtender ID="CBE" runat="server"> <atlasToolkit:ConfirmButtonProperties TargetControlID="Button1" ConfirmText="You can't see me" /> </atlasToolkit:ConfirmButtonExtender> </div> </form></body></html>