Monday, March 12, 2012

How to handle linkbutton click?

guys I've met with a problem

I need to create a linkbutton control dynamicaly within a repeater

Dim X As New RepeaterItem(0, ListItemType.Item)

Dim LB As New LinkButton
LB.Text = SomeText
LB.CommandArgument = Value
LB.CausesValidation = True
AddHandler LB.Click, AddressOf PageClick
X.Controls.Add(LB)


Rep.Controls.Add(X)

...


Protected Sub PageClick(ByVal sender As Object, ByVal e As EventArgs)

Search(3, TryCast(sender, LinkButton).CommandArgument)

End Sub

but when I click that linkbutton it doesn't fire. what I do wrong?

thanks

Make sure you are re-creating this LinkButton each and every PostBack of the Page.


Add a command name to your LinkButton something like "MyLinkButton" then in the ItemCommand repeater event check if the args, hang on I will put up a sample.

ProtectedSub rptMyRepeater_ItemCommand(ByVal sourceAsObject,ByVal eAs System.Web.UI.WebControls.RepeaterCommandEventArgs)Handles rptMyRepeater.ItemCommand

If e.CommandName ="MyLinkButton"Then
' the link button was clicked
EndIf

EndSub


Eah, I need to recreate them, it works now. Is there a way to avoid recreation on every postback?


Sure, if you wanted, you could always have some type of flag stored in your Page's ViewState collection which you can use to re-create your controls or not. However, no re-creation, no event handlers.

Labels: , , , , , , , , , , , , , , ,

How to handle dynamic control event in repeater?

Hello!

I've met with a problem. I'm building a list of products and use asp.net repeater to display it. each item has to have a LinkButton called "Remove" and I need to handle the click event somehow... :(

Any ideas how to insert a linkbutton into repeater item in a way so I can handle the click event it in the code for all of them?


Put the link button in the repeater

<asp:LinkButton ValidationGroup="Delete" ID="LinkButton1" CommandArgument='<%# Eval("myID") %>">' runat="server" CausesValidation="True"
CommandName="Delete" Text="Delete" OnClick="LinkButton1_Click"></asp:LinkButton>

protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
String idtoDelete = btn.CommandArgument;
// Run Delete
}

Labels: , , , , , , , , , , , , , ,