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 Button Click event

Dear sir,

In the above code, I am binding the data such as description of the product, and i have added one button. When I click on the button for the particular row, that row's details has to be added in a separate datatable.


<asp:DataGrid ID="dgGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateColumn HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Label1" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Description") %>' />
</ItemTemplate>
</asp:TemplateColumn>

<asp:TemplateColumn >
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CommandName="Add To Cart" Text="Add To Cart" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

Please let me know how to proceed.

Thanks in Advance,

Regards,

Arun.

How about something like this:

protected void dgGrid_ItemCommand(object source, DataGridCommandEventArgs e){Button Button1 = e.CommandSourceas Button;if (Button1 ==null) {return; }DataGridItem dgi = Button1.NamingContaineras DataGridItem;if (dgi ==null) {return; }Label Label1 = dgi.FindControl("Label1")as Label;if (Label1 ==null) {return; }string description = Label1.Text;// Do whatever you want here}

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