473,549 Members | 2,734 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamic LinkButton

In a shopping cart app, suppose a user has placed 5 orders, I want to
show him 5 LinkButtons (one for each order) so that when he clicks the
first LinkButton, he would be shown the details of his first order.
Likewise if he clicks the second LinkButton, he will be shown the
details of the second order he had placed. The Text of the LinkButtons
will be 1 2 3 etc. So this user would see 1 2 3 4 5 as the
LinkButtons.

The problem is how do I add the LinkButtons dynamically. Do I have to
first create a user control & then using Page.LoadContro l add the
LinkButtons to the ASPX page? Or is there some other way out?

Can someone suggest me how do I go about it?

Nov 9 '06 #1
13 10149
Create a link button using the New operator. Set all of its properties. Add
it to the page's Controls collection.

If you need finer control over where the buttons will appear (which I
suspect you do), add them to a panel you have placed in a particular spot.

<rn**@rediffmai l.comwrote in message
news:11******** *************@k 70g2000cwa.goog legroups.com...
In a shopping cart app, suppose a user has placed 5 orders, I want to
show him 5 LinkButtons (one for each order) so that when he clicks the
first LinkButton, he would be shown the details of his first order.
Likewise if he clicks the second LinkButton, he will be shown the
details of the second order he had placed. The Text of the LinkButtons
will be 1 2 3 etc. So this user would see 1 2 3 4 5 as the
LinkButtons.

The problem is how do I add the LinkButtons dynamically. Do I have to
first create a user control & then using Page.LoadContro l add the
LinkButtons to the ASPX page? Or is there some other way out?

Can someone suggest me how do I go about it?

Nov 9 '06 #2
<rn**@rediffmai l.comwrote in message
news:11******** *************@k 70g2000cwa.goog legroups.com...
In a shopping cart app, suppose a user has placed 5 orders, I want to
show him 5 LinkButtons (one for each order) so that when he clicks the
first LinkButton, he would be shown the details of his first order.
Likewise if he clicks the second LinkButton, he will be shown the
details of the second order he had placed. The Text of the LinkButtons
will be 1 2 3 etc. So this user would see 1 2 3 4 5 as the
LinkButtons.

The problem is how do I add the LinkButtons dynamically. Do I have to
first create a user control & then using Page.LoadContro l add the
LinkButtons to the ASPX page? Or is there some other way out?

Can someone suggest me how do I go about it?
Dead easy.

When your page loads, I'm assuming that you already know how many orders are
in the cart - mayhe you're storing the cart in a Session variable, or
fetching it from a database or whatever - doesn't really matter... The
following assumes that you've fetched it into

1) In Page_Init, not Page_Load, fetch your cart

2) For each element in the cart (order, product, whatever), create a new
LinkButton() object:

LinkButton lnkDynamic;

foreach(<whatev erin <cart>)
{
lnkDynamic = new LinkButton();
lnkDynamic.Enab leViewState = true;
lnkDynamic.ID = "lnkDynamic _" + <identifier>;
lnkDynamic.Text = "SomeText";
lnkDynamic.Comm and += new CommandEventHan dler(lnkDynamic _Process);
lnkDynamic.Comm andName = <whatever>;
lnkDynamic.Visi ble = false;
this.Controls.A dd(lnkDynamic);
}

That will have created as many individual buttons as there are elements in
your cart.

3) Create the event handler

private void lnkDynamic_Comm and(object sender, CommandEventArg s e)
{
// your code to process the individual elements goes here
// use e.CommandName to work out which button was clicked

}

4) Place the individual dynamic buttons on your form wherever they need to
be e.g. in the cells of a GridView, Repeater etc and make them visible.
Obviously you will need to adapt the above to suit your particular needs,
but it should be enough to get you started.
Nov 9 '06 #3
Mark, I don't find Intellisense list any property named Command for the
LinkButton control as you have shown in your post but of course, the
LinkButton control does have a OnCommand property! So how do I get the
CommandName of each LinkButton?

Actually what I am doing is I am getting the total no. of orders a user
has placed from the database (using a stored procedure) & returning it
in a SqlDataReader. This is the function which does that in the VB
class file:

Namespace Shop
Public Class ShopCart
Private sqlConn As New SqlConnection(" .....")
Public Function GetOrderCount(B yVal UserID As Integer) As
SqlDataReader
Dim sqlCmd As SqlCommand
Dim sqlReader As SqlDataReader

sqlCmd = New SqlCommand("Cou ntOrders", sqlConn)
sqlCmd.CommandT ype = CommandType.Sto redProcedure

Try
With sqlCmd
.Parameters.Add ("@UserID", SqlDbType.Int). Value =
UserID
End With

sqlConn.Open()
sqlReader = sqlCmd.ExecuteR eader
If (sqlReader.HasR ows) Then
Return sqlReader
Else
Return Nothing
End If
Catch ex As Exception
Throw ex
End Try
End Function
End Class
End Namespace

This is the ASPX code that invokes the above function:

<%@ Import Namespace="Shop " %>
'importing other necessary Namespaces here

Sub Page_Load(..... )
Dim boShopCart As ShopCart
Dim lnkCount As LinkButton
Dim iCount As Integer = 1
Dim sqlReader As SqlDataReader

boShopCart = New ShopCart
sqlReader = boShopCart.GetO rderCount(iUser ID)

While (sqlReader.Read )
If (sqlReader.GetV alue(0) 1) Then
iTotalOrder = sqlReader.GetVa lue(0)
Else
pnlLinks.Visibl e = False
End If
End While

For iCount = 1 To iTotalOrder
lnkCount = New LinkButton
lnkCount.ID = "lnkCount" & iCount
lnkCount.Text = iCount.ToString & "&nbsp;&nbs p;"
lnkCount.Comman dName = iCount
pnlLinks.Contro ls.Add(lnkCount )
Next
End Sub

Assuming that a user has placed 5 orders, the above ASPX code is
displaying the 5 LinkButtons 1 2 3 4 5.....no problem till this
point but how do I get the CommandName of each LinkButton.

My main intention is to get the CommandName of the LinkButtons. Prior
to this, I was using HTML hyperlinks to show 1 2 3 4 5 & passing it
as a querystring. For e.g. the href value of the hyperlink would be,
say, ShowOrder.aspx? OrderID=23&Page Num=1 so that when the user clicks
1, 1 no longer remains a hyperlink.

Mark Rae wrote:
<rn**@rediffmai l.comwrote in message
news:11******** *************@k 70g2000cwa.goog legroups.com...
In a shopping cart app, suppose a user has placed 5 orders, I want to
show him 5 LinkButtons (one for each order) so that when he clicks the
first LinkButton, he would be shown the details of his first order.
Likewise if he clicks the second LinkButton, he will be shown the
details of the second order he had placed. The Text of the LinkButtons
will be 1 2 3 etc. So this user would see 1 2 3 4 5 as the
LinkButtons.

The problem is how do I add the LinkButtons dynamically. Do I have to
first create a user control & then using Page.LoadContro l add the
LinkButtons to the ASPX page? Or is there some other way out?

Can someone suggest me how do I go about it?

Dead easy.

When your page loads, I'm assuming that you already know how many orders are
in the cart - mayhe you're storing the cart in a Session variable, or
fetching it from a database or whatever - doesn't really matter... The
following assumes that you've fetched it into

1) In Page_Init, not Page_Load, fetch your cart

2) For each element in the cart (order, product, whatever), create a new
LinkButton() object:

LinkButton lnkDynamic;

foreach(<whatev erin <cart>)
{
lnkDynamic = new LinkButton();
lnkDynamic.Enab leViewState = true;
lnkDynamic.ID = "lnkDynamic _" + <identifier>;
lnkDynamic.Text = "SomeText";
lnkDynamic.Comm and += new CommandEventHan dler(lnkDynamic _Process);
lnkDynamic.Comm andName = <whatever>;
lnkDynamic.Visi ble = false;
this.Controls.A dd(lnkDynamic);
}

That will have created as many individual buttons as there are elements in
your cart.

3) Create the event handler

private void lnkDynamic_Comm and(object sender, CommandEventArg s e)
{
// your code to process the individual elements goes here
// use e.CommandName to work out which button was clicked

}

4) Place the individual dynamic buttons on your form wherever they need to
be e.g. in the cells of a GridView, Repeater etc and make them visible.
Obviously you will need to adapt the above to suit your particular needs,
but it should be enough to get you started.
Nov 9 '06 #4
<rn**@rediffmai l.comwrote in message
news:11******** *************@h 48g2000cwc.goog legroups.com...
Mark, I don't find Intellisense list any property named Command for the
LinkButton control as you have shown in your post
Well you wouldn't - it's an event, not a property...
http://msdn2.microsoft.com/en-us/lib...n.command.aspx
but of course, the LinkButton control does have a OnCommand property!
No it doesn't - it has an OnCommand *method*, not a property...
http://msdn2.microsoft.com/en-us/lib...oncommand.aspx

You may think I'm being pedantic here, but the understanding of (the
difference between) events and properties and methods is extremely
important...
So how do I get the CommandName of each LinkButton?
Exactly as I described in my previous post...

private void lnkDynamic_Comm and(object sender, CommandEventArg s e)
{
// your code to process the individual elements goes here
// use e.CommandName to work out which button was clicked
}

This is the function which does that in the VB class file:
You mean VB.NET, of course...

And that may be the problem - my code sample was C#, and it may work
differently in VB.NET
Nov 9 '06 #5
No it doesn't - it has an OnCommand *method*, not a property

Sorry....I meant the OnCommand method (which raises the Command event)

Well I have had already a look at the 2 URLs you have cited in the
,NET2 SDK documentation but in both the articles, the app is aware of
the name of the LinkButton at design time but since I am creating the
LinkButtons dynamically, how does the app get the name of the
LinkButtons?

In simple words, since the following line

lnkCount.Comman d += New CommandEventHan dler(lnkDynamic _Process)

won't work; so what should be the code that should replace the above
line in the For...Next loop? I guess I will have to use RaiseEvent but
I don't know how to go about it.
So how do I get the CommandName of each LinkButton?

Exactly as I described in my previous post..
Well I am aware of that but as already said before how do I invoke the
sub lnkDynamic_Comm and in the first place when a LinkButton is clicked.
What should be the code for invoking lnkDynamic_Comm and?

I hope you understand where have I got stuck.

Mark Rae wrote:
<rn**@rediffmai l.comwrote in message
news:11******** *************@h 48g2000cwc.goog legroups.com...
Mark, I don't find Intellisense list any property named Command for the
LinkButton control as you have shown in your post

Well you wouldn't - it's an event, not a property...
http://msdn2.microsoft.com/en-us/lib...n.command.aspx
but of course, the LinkButton control does have a OnCommand property!

No it doesn't - it has an OnCommand *method*, not a property...
http://msdn2.microsoft.com/en-us/lib...oncommand.aspx

You may think I'm being pedantic here, but the understanding of (the
difference between) events and properties and methods is extremely
important...
So how do I get the CommandName of each LinkButton?

Exactly as I described in my previous post...

private void lnkDynamic_Comm and(object sender, CommandEventArg s e)
{
// your code to process the individual elements goes here
// use e.CommandName to work out which button was clicked
}

This is the function which does that in the VB class file:

You mean VB.NET, of course...

And that may be the problem - my code sample was C#, and it may work
differently in VB.NET
Nov 9 '06 #6
lets take everything that was already suggested and VB'ify it. That
will hopefully make things a little more clear. Take note of #1 below.
Your dynamic buttons' events will not fire if they are not recreated
during page_init. Thats why it is so important that you fetch the cart
during this page event instead of during load. Best I can do. Hope it
helps.

1) In Page_Init, not Page_Load, fetch your cart

2) For each element in the cart (order, product, whatever), create a
new button.

Dim lnkDynamic As LinkButton

foreach(<whatev erin <cart>)
lnkDynamic = new LinkButton()
lnkDynamic.Enab leViewState = true
lnkDynamic.ID = "lnkDynamic _" + <identifier'Ide ntifier can be
your order# or whatever your want
lnkDynamic.Text = "SomeText"
AddHandler lnkDynamic.Comm and, AddressOf lnkDynamic_Comm and
lnkDynamic.Comm andName = "AnyTextYouWant "
lnkDynamic.Visi ble = false
Me.Controls.Add (lnkDynamic)
Next

That will have created as many individual buttons as there are elements
in
your cart.

3) Create the event handler
Public Sub lnkDynamic_Comm and(sender As object, e As CommandEventArg s)
' your code to process the individual elements goes here
' use e.CommandName to work out which button was clicked
' You could put the order number into the command name
' you could also cast sender to a LinkButton and check its ID if
you want. many different ways.
If e.CommandName = "1" Then
'Do stuff for 1
End If

or maybe

Dim lb As LinkButton
lb = DirectCast(send er, LinkButton) 'or whatever your favorite
method is
If lb.ID == "1" Then 'or whatever the heck you want to do
'Some stuff
End If
End Sub
4) Place the individual dynamic buttons on your form wherever they need
to
be e.g. in the cells of a GridView, Repeater etc and make them visible.

Nov 9 '06 #7
<rn**@rediffmai l.comwrote in message
news:11******** **************@ e3g2000cwe.goog legroups.com...
>No it doesn't - it has an OnCommand *method*, not a property

Sorry....I meant the OnCommand method (which raises the Command event)
OK.
In simple words, since the following line

lnkCount.Comman d += New CommandEventHan dler(lnkDynamic _Process)

won't work;
Yes it will, but in C#... Gozirra has converted my code into VB.NET for
you...
I hope you understand where have I got stuck.
See Gozirra's post...
Nov 9 '06 #8
Gozirra, that's EXACTLY what I was looking out for (the AddHandler
lnkDynamic.Comm and, AddressOf lnkDynamic_Comm and line). Thanks a lot.

You as well as Mark have repeatedly stressed on fetching the cart (if I
am not mistaken, by "fetching the cart", you & Mark mean getting the
no. of orders a user has placed & the details of each & every order) in
the Page_Init sub & NOT in the Page_Load sub. But what I find is even
if I place the ASPX code I have shown in post #4 in this thread in the
Page_Load sub & NOT in the Page_Init sub, then not only do the
LinkButtons get recreated after each PostBack but also the events
associated with the LinkButtons (in this case, the Command event) fire
correctly after every PostBack. So why have you (& Mark) stressed on
fetching the cart in the Page_Init sub & NOT in the Page_Load sub?

Could you please clarify this point?
Gozirra wrote:
lets take everything that was already suggested and VB'ify it. That
will hopefully make things a little more clear. Take note of #1 below.
Your dynamic buttons' events will not fire if they are not recreated
during page_init. Thats why it is so important that you fetch the cart
during this page event instead of during load. Best I can do. Hope it
helps.

1) In Page_Init, not Page_Load, fetch your cart

2) For each element in the cart (order, product, whatever), create a
new button.

Dim lnkDynamic As LinkButton

foreach(<whatev erin <cart>)
lnkDynamic = new LinkButton()
lnkDynamic.Enab leViewState = true
lnkDynamic.ID = "lnkDynamic _" + <identifier'Ide ntifier can be
your order# or whatever your want
lnkDynamic.Text = "SomeText"
AddHandler lnkDynamic.Comm and, AddressOf lnkDynamic_Comm and
lnkDynamic.Comm andName = "AnyTextYouWant "
lnkDynamic.Visi ble = false
Me.Controls.Add (lnkDynamic)
Next

That will have created as many individual buttons as there are elements
in
your cart.

3) Create the event handler
Public Sub lnkDynamic_Comm and(sender As object, e As CommandEventArg s)
' your code to process the individual elements goes here
' use e.CommandName to work out which button was clicked
' You could put the order number into the command name
' you could also cast sender to a LinkButton and check its ID if
you want. many different ways.
If e.CommandName = "1" Then
'Do stuff for 1
End If

or maybe

Dim lb As LinkButton
lb = DirectCast(send er, LinkButton) 'or whatever your favorite
method is
If lb.ID == "1" Then 'or whatever the heck you want to do
'Some stuff
End If
End Sub
4) Place the individual dynamic buttons on your form wherever they need
to
be e.g. in the cells of a GridView, Repeater etc and make them visible.
Nov 9 '06 #9
<rn**@rediffmai l.comwrote in message
news:11******** **************@ h48g2000cwc.goo glegroups.com.. .
Gozirra, that's EXACTLY what I was looking out for (the AddHandler
lnkDynamic.Comm and, AddressOf lnkDynamic_Comm and line). Thanks a lot.
Cool.
You as well as Mark have repeatedly stressed on fetching the cart (if I
am not mistaken, by "fetching the cart", you & Mark mean getting the
no. of orders a user has placed & the details of each & every order) in
the Page_Init sub & NOT in the Page_Load sub. But what I find is even
if I place the ASPX code I have shown in post #4 in this thread in the
Page_Load sub & NOT in the Page_Init sub, then not only do the
LinkButtons get recreated after each PostBack but also the events
associated with the LinkButtons (in this case, the Command event) fire
correctly after every PostBack. So why have you (& Mark) stressed on
fetching the cart in the Page_Init sub & NOT in the Page_Load sub?

Could you please clarify this point?
The salient point here is not the fetching of the cart per se - it's the
dynamic creation of webcontrols.

Generally speaking, dynamic control creation can only be pretty much
guaranteed to work when done in Page_Init, not Page_Load - if you have got
it to work in Page_Load, then you're lucky... Change one little thing in
your app and you might find it stops working...

However, since the dynamic creation of the webcontrols in this particular
instance is directly related to the cart, fetching the cart is required
before the controls can be dynamically created, which is why the cart needs
to be fetched in Page_Init, not Page_Load.

It's the same scenario with e.g. DropDownList controls - populate them in
Page_Init, not Page_Load otherwise you may just find that your ViewState
stops working properly.
Nov 9 '06 #10

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

Similar topics

1
3846
by: Bill | last post by:
I'm trying to dynamically build several linkbuttons and wire them up to a method called OnLinkClick . . . For the life of me, I don't understand why the code below isn't firing the event. LinkButton lbBC = new LinkButton(); phBreadCrumb.Controls.Add(lbBC); lbBC.Font.Size = 11; lbBC.CssClass = "lnkBtnBreadCrumbProperties";
3
36673
by: CodeRazor | last post by:
I am creating an aspx page using C# and would like to be able to dynamically create linkbuttons that all run the same fuction on the click event. However, I would like the function to accept a single argument (in this case the file name) to identify which button was clicked. I am using the Command event handler. The link buttons load...
1
2502
by: RSB | last post by:
Hi Everyone, I have a collection of items and i am generating a Dynamic Table based on this Collection and i am also adding a Remove Linkbutton at the End for Each Row. I have created a function called GenerateList and i call this in the OnPreRender Now every thing is fine but i am not able to Capture the Event for the "Remove This" all...
2
3854
by: hn | last post by:
Hi, I have linkbuttons created dynamically and they display fine on the web page. However, when I click on the those link buttons, the event doesn't fire. Please tell me what's wrong with the following code. Thanks. Dim lbtnQuestion As LinkButton = New LinkButton lbtnQuestion.Text = "Question " & (j + 1).ToString()
0
1541
by: BLiTZWiNG | last post by:
I have scoured the web to no avail. Any post that resembles my problem has no answer. I have an asp table on my page. I add rows and cells to it at run time with info provided from a database in a custom function. To one of those cells I add a new LinkButton, then wire a command event handler to it, which calls the custom function, thus...
4
10595
by: Fueled | last post by:
Hi everyone! I've made quite a lot of research on this, and I've tried a couple of proposed solutions. Nothing has worked for me, but I feel there's not much I'm missing. So I'm turning to this group and its experts for answers. So : - I've got a main page (main.aspx) - On this page, I've got a button (btnArchive), on whose click I...
1
2496
by: Andrew Robinson | last post by:
I have a <asp:table> control with a large number of dynamically created LinkButtons. I am using the command event, command name and command argument values in my LinkButtons to trigger actions after the post back. The table is dynamically generated based on a key field that is stored in ViewState. This key field is updated by several other...
2
1905
by: Mufasa | last post by:
I have code to dynamically generate some link buttons (It's not know how many are needed until runtime.) I am adding the linkbutton to a cell in a table and the adding works fine. It's firing of the event doesn't seem to be happening. Am I missing something? Here's the code: To create the link button:
2
5845
by: michaelmaria313 | last post by:
Hi All, I am brand new (like 2 weeks) to ASP.NET and VB. I have a series of linkbuttons that are generated dynamically inside a repeater. I need the background color of the selected linkButton to change and remain a new color when clicked. I thought that the ItemCommand property of the repeater would do the trick, but it doesn't. Here is...
0
7451
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...
0
7960
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7475
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...
0
5089
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...
0
3501
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3483
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1944
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
1
1061
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
766
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...

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.