Как добавить событие onclick к программно созданной кнопке ссылки в vb.net

Я хочу отображать продукты, которые я получаю из своей БД, используя набор данных в таблице динамически, потому что количество продуктов в каждом магазине различно, и когда пользователь нажимает на продукт из таблицы, я отображаю информацию о продукте, по которому щелкнули экран.

проблема в том, что я добавил кнопку ссылки программно в каждую ячейку таблицы, но обработчик события щелчка не работает.

Пожалуйста, как я могу добавить кнопку ссылки и динамически щелкнуть обработчик события? и как я могу получить идентификатор нажатой кнопки внутри метода обработчика событий (ShowProductDetails)?

это мой код

Products.aspx

 </asp:Content>
   <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <table  style=" width: 700px;" align="center">
<tr style="width:100%;">

<td align="center" width="50%" >Stores </td>
<td align="right" width="50%" >
<asp:DropDownList ID="StoresDDL" runat="server" AutoPostBack="True" Width="120px">
</asp:DropDownList>
</td>

</tr>

<tr>
<td >
<asp:table id="ProductsTBL" runat ="server" style="width: 700px;" 
        align="center" BorderStyle="Groove" BorderWidth="3px">
</asp:table>
</td>
</tr>

<tr>
<td>
<asp:Panel  runat ="server" id="ProductDetails_Panel" visible ="false">

<asp:Label ID="selectedProduct" runat ="server" Visible="false" ></asp:Label>
</asp:Panel>
</td>



</tr>
    </table>


   </asp:Content>

Products.aspx.vb

 Imports System.Data



Partial Class Admin_ViewProducts
     Inherits System.Web.UI.Page


Dim con As New Conection
Dim ds_Products As New DataSet 
Dim dr_Products As DataRow
Dim ds_Stores As New DataSet
Dim dr_Stores As DataRow


Dim sB As New LinkButton()


Protected Sub StoresDDL__Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles StoresDDL.Init

    StoresDDL.Items.Clear()
    StoresDDL.Items.Add("Select a store")
    StoresDDL.DataValueField = 0

    Try

            ds_Stores = con.get_data("select storeid , storeName from Store ")

        End If

        Dim x As Integer = 1
        For Each Me.dr_stores In ds_stores.Tables(0).Rows
            If (dr_stores.IsNull(0) = False) Then
                StoresDDL.Items.Add(dr_stores.Item(1))

                StoresDDL.Items(x).Value = dr_stores.Item(0)

                x = x + 1
            End If

        Next

    Catch ex As Exception

    End Try
End Sub

Protected Sub StoresDDL_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles StoresDDL.SelectedIndexChanged


    ds_products = con.get_data("select productid ,productName from Product where storeid=" & StoresDDL.SelectedValue ")
    Dim y As Integer = 1

    Dim NOClmns As Integer = 3
    Dim NOCells As Integer = ds_products.Tables(0).Rows.Count
    Dim NORows As Integer = Math.Round(NOCells / 3, MidpointRounding.AwayFromZero)


    ' Current row count
    Dim rowCtr As Integer
    ' Current cell counter.
    Dim cellCnt As Integer

    Dim productCount As Integer = 0
    While productCount <> ds_products.Tables(0).Rows.Count
        For rowCtr = 1 To NORows
            Dim tRow As New TableRow()
            For cellCount = 1 To 4 'For NOCells = 1 To cellCnt

                Dim tCell As New TableCell()
                'Dim s As New HyperLink()
                sB = New LinkButton()
                sB.ID = ds_products.Tables(0).Rows(productCount).Item("productName").ToString
                sB.Text = ds_products.Tables(0).Rows(productCount).Item("productName").ToString

                AddHandler sB.Click, AddressOf Me.ShowProductDetails

                tCell.Controls.Add(sB)
                tRow.Cells.Add(tCell)
                productCount += 1
            Next cellCount   'NOCells
            ' Add new row to table.
            ProductsTBL.Rows.Add(tRow)

        Next rowCtr

    End While
End Sub

Protected Sub ShowProductDetails(ByVal sender As System.Object, ByVal e As System.EventArgs)



    ProductDetails_Panel.Visible = True
    selectedProduct.Visible = True
    selectedProduct.Text = "test"


     End Sub
 End Class

1 ответ

Чтобы сделать это, вам нужно использовать командное событие для кнопки ссылки и передать CommandArgument, идентификатор продукта.

Так:

sb.CommandArgument = ds_products.Tables(0).Rows(productCount).Item("productID")
sb.CommandName = "clicked"
sb.OnCommand="LinkButton_Command" 

Затем добавьте событие в код позади:

   Sub LinkButton_Command(sender As Object, e As CommandEventArgs) 
      If e.CommandName = "clicked" Then
           Process Request
      End IF
   End Sub

Но если бы это был я, я бы связался с DataGrid или Repeater, а не создал бы свою собственную таблицу...

Другие вопросы по тегам