473,756 Members | 3,566 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

.Net 2.0 / AJAX / Dynamically adding controls to the page

Hi all,

I played with my first bit of AJAX the other week and was pleasantly
surprised that I achieved my goal..now I'd like to try something else..

Question...

If I have an updatePanel, and lets say I have a button as a trigger which
runs a function in my code behind to add a textbox to the updatePanel, when
the form is submitted does this control actually "exist" as such on the
page? ie, will I be able to talk to it in .net via myTextBox.Text etc or
will I have to rely on Response.Form(" myTextBox") to pick up the values...

Has anyone done something similar?

I basically need the user to be able to add resources to their profile, each
resource has an access level and a parameter that they will select, so
instead of a text box I would have two drop down menus populated with items,
I just wondered how you then interact with them once posted...

Any thoughts/help appreciated..

Regards

Rob
Feb 21 '07 #1
4 2549
Hi Rob,

It's very similar situation to dynamic controls. Dynamic controls are not
part of compiled control tree, so every time you make a request and postback
you have to recreate them yourself. Of course you can declare variables
within page class to access controls later on in page lifecycle:

public partial class MyPage : System.Web.UI.P age
{

private TextBox dynamicTextBox;
protected void Page_Init(objec t sender, EventArgs e)#
{
dynamicTextBox = new TextBox();
dynamicTextBox. ID = “dynamicTxt†ť;
myupdatePanel.C ontrols.Add(dyn amicTextBox);
}
protected void myButton_Click( object sender, EventArgs e)
{
string text = this. dynamicTextBox;
// do something with text
}

I also reckon it should work with AJAX update panel because it’s simply
makes post request with all forms including viewstate related hidden fields.
It definitely would not work with get asynchronous requests (see AJAX methods
marked with WebMethod() attribute) as AJAX supports them as well.

--
Milosz
"Rob Meade" wrote:
Hi all,

I played with my first bit of AJAX the other week and was pleasantly
surprised that I achieved my goal..now I'd like to try something else..

Question...

If I have an updatePanel, and lets say I have a button as a trigger which
runs a function in my code behind to add a textbox to the updatePanel, when
the form is submitted does this control actually "exist" as such on the
page? ie, will I be able to talk to it in .net via myTextBox.Text etc or
will I have to rely on Response.Form(" myTextBox") to pick up the values...

Has anyone done something similar?

I basically need the user to be able to add resources to their profile, each
resource has an access level and a parameter that they will select, so
instead of a text box I would have two drop down menus populated with items,
I just wondered how you then interact with them once posted...

Any thoughts/help appreciated..

Regards

Rob
Feb 21 '07 #2
"Milosz Skalecki [MCAD]" wrote ...
It's very similar situation to dynamic controls. Dynamic controls are not
part of compiled control tree, so every time you make a request and
postback
you have to recreate them yourself.
Hi Milosz,

Thats kinda what I was guessing, bit of a pain but I guess I can work around
that.

One more thing - as I mentioned the users can select additional resources to
add to the profile, this is a long list, so I'm probably going to have to
fire it up in a popup window, are you aware of any way to use AJAZ/.Net so
that my popup can talk to the updatePanel on the parent page? I'm probably
trying to run before I can walk abit here, so please excuse my ignorance,
but what I would want to do I guess is launch a popup from a link or button,
this hits the database, lists all my resources as links with a querystring
parameter of the resource id. Once clicked I would like this to then act as
the "trigger" on the parent page using the parameter from the link to run
code to add the control the parent page..

Any thoughts?

Part of me is thinking "Rob, thats such a stupid question" but obviously I
can do this with a normal postback, but I dont really want the parent page
to reload, and I dont really want to have to write a load of code that
checks to see if the parent page is just loading, or loading as a result of
the child popup click event.

Any help appreciated.

Regards

Rob
Feb 21 '07 #3
Hi Rob,

Of course it is possible. I prepared a simple exmaple to show you which way
to go. Please note, I used AJAX predecessor ATLAS which should (in this case)
be fine. Example consists of two pages - main where you click to select
employees from the list located in a popup window, second page is just a
mentioned popup. In order to post the code in two pieces, i used script runat
server, but ideally you could move it to code behind.

-- begin RobsmainPage.as px --

<%@ Page Language="C#" AutoEventWireup ="true"
CodeFile="RobsM ainPage.aspx.cs " Inherits="RobsM ainPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitl ed Page</title>
</head>
<body>
<form id="form1" runat="server">
<atlas:ScriptMa nager ID="ScriptManag er" EnablePartialRe ndering="True"
runat="server" />
<atlas:UpdatePa nel ID="UpdatePanel " RenderMode="Blo ck" runat="server"
Mode="Always">
<ContentTemplat e>
<asp:PlaceHolde r runat="server" ID="container" />
<asp:Button runat="server" ID="btnRefresh " Width="0" Height="0"
OnClick="btnRef resh_Click" />
<asp:HiddenFiel d runat="server" ID="selectedEmp loyeeId" />
</ContentTemplate >
</atlas:UpdatePan el>
<asp:Button runat="server" ID="btnSelect" Text="Select Employee to
Update..." OnClientClick=" SelectEmployee( ); return false;" />
<asp:Button runat="server" ID="btnSubmit" Text="Submit Selection"
OnClick="btnSub mit_Click" />

<script type="text/javascript">
//<!--

function EployeeSelected (id)
{

var hidden = $('<%= selectedEmploye eId.ClientID %>');
if (hidden)
hidden.value = id;

var btn = $('<%= btnRefresh.Clie ntID %>');
if (btn)
{
btn.click();
}
}

function SelectEmployee( )
{
var win = window.open('Ro bsPopupPage.asp x', 'RobsPopupPage' ,
'width=450,heig ht=350');
if (!win)
{
alert('Disable popup blocker please!');
}
}

// -->
</script>

<script runat="server">
protected void Page_Load(objec t sender, EventArgs e)
{
RecereateList() ;
}
protected void btnRefresh_Clic k(object sender, EventArgs e)
{
int id;
if (int.TryParse(s electedEmployee Id.Value, out id))
{
SelectedEmploye eIds.Add(id);
AddEmployeeToLi st(id);
}
}
private void AddEmployeeToLi st(int id)
{
Label label = new Label();
label.Text = "Employee selected with id = " + id.ToString();
label.Style.Add ("display", "block");

container.Contr ols.Add(label);
}
private void RecereateList()
{
foreach (int id in SelectedEmploye eIds)
{
AddEmployeeToLi st(id);
}
}
private ArrayList SelectedEmploye eIds
{
get
{
ArrayList value = (ArrayList)View State["SelectedEmploy eeIds"];
if (value == null)
{
value = new ArrayList();
ViewState["SelectedEmploy eeIds"] = value;
}
return value;
}
}
protected void btnSubmit_Click (object sender, EventArgs e)
{
// do something with selected employee ids:

foreach (int id in SelectedEmploye eIds)
{
// whatever
}
}
</script>

</form>
</body>
</html>
-- end RobsMainPage.as px --

-- begin RobsPopupPage.a spx --
<%@ Page Language="C#" AutoEventWireup ="true"
CodeFile="RobsP opupPage.aspx.c s" Inherits="RobsP opupPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitl ed Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<script type="text/javascript">
//<!--
function PerformSelect(i d)
{
if (window.opener)
{
if (window.opener. EployeeSelected )
window.opener.E ployeeSelected( id);
window.close();
}
}
//-->
</script>

<script runat="server">


protected void Page_Load(objec t sender, EventArgs e)
{
if (!IsPostBack)
{
employees.DataS ource = GetEmployees();
employees.DataB ind();
}
}

public System.Data.Dat aTable GetEmployees()
{
System.Data.Dat aTable table =
new System.Data.Dat aTable();
System.Data.Dat aRow row = null;

table.Columns.A dd("EmployeeId" , typeof(int));
table.Columns.A dd("EmployeeNam e", typeof(string)) ;
table.Columns.A dd("EmployeeRol e", typeof(string)) ;

for (int i = 0; i < 10; i++)
{
row = table.NewRow();
row[0] = i;
row[1] = "employee " + i.ToString();
row[2] = (i % 3 == 0) ? "Manager" : "Clerk";

table.Rows.Add( row);
}

return table;
}

</script>

<asp:GridView runat="server" ID="employees" AutoGenerateCol umns="false">
<Columns>
<asp:TemplateFi eld>
<HeaderTemplate >
Name
</HeaderTemplate>
<ItemTemplate >
<a href="javascrip t:PerformSelect ('<%# Eval("EmployeeI d") %>');"><%#
Eval("EmployeeN ame")%></a>
</ItemTemplate>
</asp:TemplateFie ld>
<asp:BoundFie ld HeaderText="Epl oyee's Role" DataField="Empl oyeeRole" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>

-- end RobsPopupPage.a spx --

Hope this helps

Milosz
"Rob Meade" wrote:
"Milosz Skalecki [MCAD]" wrote ...
It's very similar situation to dynamic controls. Dynamic controls are not
part of compiled control tree, so every time you make a request and
postback
you have to recreate them yourself.

Hi Milosz,

Thats kinda what I was guessing, bit of a pain but I guess I can work around
that.

One more thing - as I mentioned the users can select additional resources to
add to the profile, this is a long list, so I'm probably going to have to
fire it up in a popup window, are you aware of any way to use AJAZ/.Net so
that my popup can talk to the updatePanel on the parent page? I'm probably
trying to run before I can walk abit here, so please excuse my ignorance,
but what I would want to do I guess is launch a popup from a link or button,
this hits the database, lists all my resources as links with a querystring
parameter of the resource id. Once clicked I would like this to then act as
the "trigger" on the parent page using the parameter from the link to run
code to add the control the parent page..

Any thoughts?

Part of me is thinking "Rob, thats such a stupid question" but obviously I
can do this with a normal postback, but I dont really want the parent page
to reload, and I dont really want to have to write a load of code that
checks to see if the parent page is just loading, or loading as a result of
the child popup click event.

Any help appreciated.

Regards

Rob
Feb 21 '07 #4
"Milosz Skalecki [MCAD]" wrote ...
Of course it is possible. I prepared a simple exmaple to show you which
way to go.
[snip]

WOW! Hi Milosz,

Thank you so much for spending your time doing that for me, I will be trying
it out in just a sec - I think the clue that I needed was the hidden boxes
on the parent page, and then the javascript functions to pass the value
around.

Thank you very much,

Regards

Rob
Feb 22 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
5494
by: Mark Denardo | last post by:
I'm trying to dynamically create and add controls to a web page: Label obj1 = new Label(); DropDownList obj2 = new DropDownList(); Controls.Add(obj1); Controls.Add(obj2); But I get the following error when the DDL is added (but not the Label): "Control 'ctl07' of type 'DropDownList' must be placed inside a form tag
1
2470
by: AndiSmith | last post by:
Hi guys, I wondered if anyone could help me with this problem, or even shed some light on the direction I need to take to resolve it? I'm using .NET 2.0 (C# flavor) to build a large user-based website. I've created an AJAX based user control, which is dynamically placed on a page (once, or multiple times) if the user has the correct permissions to receive it. It contains two drop down lists - employee value and partner value; and a...
5
1857
by: Gui | last post by:
Hi, I'm working in C# .net 2005 with Ajax. I have a page that loads dynamic user controls depending on the scenario. In those user controls, I create dynamic linkbuttons. The user controls are loaded on the .aspx PageLoad and the linkbuttons are created on the .ascx PageLoad. The problem I have is that those linkbuttons don't work on the first click. I have to make 2 clicks to have their event fired. What can I do for that ? Thanks.
1
2199
by: John Straumann | last post by:
Hello all: I am a CRM Solution Architect so not a .NET expert by any means. I am working with a customer who needs to modify the Advanced find in CRM which works as shown here: http://thestraumanns.mine.nu/af.html Screen 1 shows a saved query loaded in the tool, and you can add query rows by clicking the "Select" link which will display Screen 2. If you then
1
3404
by: =?Utf-8?B?TW9oc2luIEtoYW4=?= | last post by:
Hi, I am working on a website where i am creating Horizontal Menus Dynamically from database as per rights available to the user. I have several UserControls. And the Menu control also brings UserControl's URL stored in Database while Page load. There is a TabContainer control below the Menu Control. Now i want to add corresponding UserControl dynamically when user clicks on
1
4910
by: semomaniz | last post by:
I have a form where i have created the form dynamically. First i manually added a panel control to the web page. Then i added another panel dynamically and inside this panel i created tables. I have set text boxes and labels inside the table rows. I then added a button. All of these are done through code. The problem that i am having is i can get the value from a text box with resides inside the first panel (out side of panel that is...
7
6668
by: RichB | last post by:
I am trying to get to grips with the asp.net ajaxcontrol toolkit, and am trying to add a tabbed control to the page. I have no problems within the aspx file, and can dynamically manipulate a tabcontainer which has 1 panel already, however I want to try create the TabPanels dynamically. I followed the advice here: http://www.asp.net/learn/ajax-videos/video-156.aspx (3rd comment - Joe Stagner)
0
2917
by: sanrek | last post by:
Hi Folks, Slider control is driving me nuts, below is the code from my test page's page load event, nothing great about code, I have a place holder control into which I am adding a table which has three rows with a slider control in each row created dynamically. The problems what I have are 1) handler image does not get displayed, I have set the handleImageUrl and have moved the handlecssclass and railcssclass into local style sheet 2)...
3
8612
by: robbp | last post by:
Hi guys, I have a problem where i have a web page (inheriting from a master page which contains the scriptmanager control) containing a dynamically created wizard control. At runtime i add the steps from custom controls i have created, basically simulating content etc. Now - when i try to add ajax extenders to the custom controls it errors out on load and says that the controls havent been registered - have scoured the web but cant seem to...
0
9456
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9275
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10034
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9843
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7248
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6534
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3805
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3358
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2666
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.