0

I have searched this site for what I need, but none of the answers just quite fits my needs. So here's the deal:

I am dynamically loading a usercontrol to aspx page along with some buttons like this:

Dim uc As UserControl
Dim btns As New List(Of LinkButton)
uc = LoadControl("path_to_ascx")
btns.Add(New LinkButton With {.ID = "btnid", .Text = "Sometext"})
uc.GetType().GetProperty("tblButtons").SetValue(uc, btns, Nothing)
holder2.Controls.Add(uc) 'holder2 is an id of a PlaceHolder

An this work perfectly fine. The buttons show on the page as expected. Now I am having trouble, how to tell these buttons to rise an event written in aspx page, to which a usercontrol is being loaded to.

Public Sub btnClick(sender As Object, e As EventArgs)
    'do stuff
End Sub

Why I want to achieve this? Because I have a pretty complex UserControl which I want to reuse as much as possible, but buttons will do different stuff on every aspx page this UserControl will be loaded to.

Thanks

T.S.
  • 18,195
  • 11
  • 58
  • 78
  • The thing is, your question is already answered here https://stackoverflow.com/questions/7713242/asp-net-dynamically-button-with-event-handler. Al you have to do is to google "asp.net dynamic buttons with events" – T.S. Aug 03 '17 at 21:37
  • @T.S., I don't think the link provided solves my problem. The buttons are declared in aspx, but they are sent trough a property to usercontrol and they are added to gridview cell. Also, how to set a command argument based on gridview row value. And those buttons must fire event written in aspx. Is this even possible? – VR46theDoc Aug 04 '17 at 07:13

1 Answers1

0

I have solved my problem. In UserControl, I added dynamic buttons to every row on OnRowCreated event.

I was loading UserControl to aspx with buttons like in my question, I just added an ID property to my usercontrol:

Dim uc As UserControl
Dim btns As New List(Of LinkButton)
uc = LoadControl("path_to_ascx")
btns.Add(New LinkButton With {.ID = "btnid", .Text = "Sometext", .CommandName = "cmdName"})
uc.ID = "UserControl1" 'here I added ID property
uc.GetType().GetProperty("tblButtons").SetValue(uc, btns, Nothing)
holder2.Controls.Add(uc) 'holder2 is an id of a PlaceHolder

And after I add an EventHanlder like this:

AddHandler TryCast(holder2.FindControl("UserControl1").FindControl("grid"), GridView).RowCommand, AddressOf grid_RowCommand
'grid is the ID of GrdiView in UserControl

And here is the event for gridview rowCommand written in aspx code behind:

Protected Sub grid_RowCommand(sender As Object, e As GridViewCommandEventArgs)
    If e.CommandName = "someCmdName" Then
        'do stuff
    Else
        'do somthing else
    End If
End Sub

Maybe my question was not good enough, because I did not mention, that I will be loading buttons to gridview row on rowCreated event and hook them up to RowCommand for wich I apologise.

If someone knows another way to do this, it would be much appreciated to share.

Regards