views:

51

answers:

1

How may one get information that was used to programatically generate asp controls?

For example, I pulled a DataTable of user objects from the database and have organized them on a page, listing groupings such as a list of employees directly under the employer for each employer. On the page, I list each user's Username as a LinkButton. When I click one of these employees, I want to redirect the page (which is easy) and set a session variable to the selected user's UserId (which seems not so easy). How can I pull this UserId value back? These elements are not hard-coded with nice names (as they are generated in a for each loop).

Code from comment below:

Dim lnkbtnPm As New LinkButton ' is my link button. '
lnkbtnPm.Text = pmDr.Item("Username") ' where pmDr is my datarow. '
lnkbtnPm.CommandArgument = pmDr.Item("UserId")     
lnkbtnPm.CommandName = "CommandNameHere"
panelToAddControlTo.Controls.Add(lnkbtnPm)

Thanks :)

+2  A: 

I think this is what you would use the CommandName and CommandArgument properties of the LinkButton for. Assign the user id as CommandArgument and a suitable string as CommandName and hook up the Command event to an event handler:

Sub LinkButton_Command(sender As Object, e As CommandEventArgs) 
    ' e.CommandArgument will contain the user id '
End Sub

Update

The problem is that the event handler is never attached. Use AddHandler to do that:

Dim lnkbtnPm As New LinkButton 
lnkbtnPm.Text = pmDr.Item("Username") ' where pmDr is my datarow. '
lnkbtnPm.CommandArgument = pmDr.Item("UserId")     
lnkbtnPm.CommandName = "CommandNameHere"
AddHandler lnkbtnPm.Command, AddressOf LinkButton_Command
panelToAddControlTo.Controls.Add(lnkbtnPm)
Fredrik Mörk
I have attempted this, but the subroutine does not appear to get called when the link buttonis clicked. Is it possible that programatically adding the link button is not giving it the runat="server" attribute?
Chris
How do you add the LinkButton controls? Do you attach the event handler to them?
Fredrik Mörk
Dim lnkbtnPm As New LinkButton is my link button. lnkbtnPm.Text = pmDr.Item("Username") where pmDr is my datarow. lnkbtnPm.CommandArgument = pmDr.Item("UserId") lnkbtnPm.CommandName = "CommandNameHere" panelToAddControlTo.Controls.Add(lnkbtnPm)
Chris
that showed up way uglier than I'd hoped. Hopefully it is still legible. Maybe I haven't attached an event handler?
Chris
This is awesome. Thanks so much for your help. My only final standing issue with this is I cannot use the PostBackUrl attribute (it posts back before calling the event). Is there any alternate that you're aware of? This is correct, so I'll accept it now.
Chris
Sorry, can't help you with the PostBackUrl issue; not really a web developer ;o)
Fredrik Mörk
All is well, I got it :) I added a Server.Transfer inside of the event, rather than attaching the PostBackUrl attribute. Thanks again :)
Chris