How to access a button inside a list? specially using button_click to perform an action

I have this simplified code:

<asp:ListView ID="ListView1" runat="server" DataSourceID="sqldatasource1"> <ItemTemplate> <asp:Button ID="ButtonTest" runat="server" BackColor="Silver" Text="Add to Cart" /> </ItemTemplate> </asp:ListView> 

I am trying to run the code behind the button, but I do not know how to do it. I can’t access it in the list. Not that it matters, but I'm trying to get information from the current list (product identifier) ​​and pass it to the next page.

Does anyone know how to approach this with the exact code? Thanks!

+4
source share
2 answers

You want an ItemCommand event. You give your button the command name, command argument (if you want), and then listen to the ItemCommand event in the ListView

 <asp:ListView ID="ListView1" runat="server" OnItemCommand="DoTheCommand" DataSourceID="sqldatasource1"> <ItemTemplate> <asp:Button CommandName="Foo" CommandArgument='<%#Eval("SomeDataBoundProperty")%>' ID="ButtonTest" runat="server" BackColor="Silver" Text="Add to Cart" /> </ItemTemplate> </asp:ListView> 

And in your code behind:

 void DoTheCommand(object sender, ListViewCommandEventArgs e) { string commandName = e.CommandName; object commandArg = e.CommandArgument; ListViewItem selectedItem = e.Item; int dataItemIndex = selectedItem.DataItemIndex; if (commandName == "Foo") { //and so on } } 
+2
source

U can use the ListView ItemCommand event in code named commandName and command argument set to aspx.

 <asp:ListView ID="ListView1" runat="server" DataSourceID="sqldatasource1"> <ItemTemplate> <asp:Button ID="ButtonAdd" runat="server" BackColor="Silver" CommandName="cAdd" CommandArgument= '<%# Eval("ProductId") %>' Text="Add to Cart" /> 

 Protected Sub ListView1_OnItemCommand(ByVal sender As Object, _ ByVal e As ListViewCommandEventArgs) Handles Listview1.ItemCommand If String.Equals(e.CommandName, "cAdd") Then Dim ProductId as integer = e.CommandArgument 'your code End If End Sub 
0
source

Source: https://habr.com/ru/post/1384244/


All Articles