vb.net以编程方式将链接按钮添加到datagrid - 单击事件不会触发

时间:2011-10-28 14:54:32

标签: vb.net data-binding onclick

我有一个数据网格,我在程序上在ItemDataBound上添加了一个链接按钮。

Protected Sub dgCounts_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgCounts.ItemDataBound

            For i As Integer = 1 To (e.Item.Cells.Count - 1)

                Dim lb As New LinkButton
                lb.CommandArgument = aryDealers(i)
                lb.Text = e.Item.Cells(i).Text
                lb.CausesValidation = False
                AddHandler lb.Click, AddressOf lb_Click

                If e.Item.Cells(i).Text.Trim.Length > 0 Then
                    e.Item.Cells(i).Controls.Add(lb)
                End If

            Next
End Sub

Protected Sub lb_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lb As LinkButton = CType(sender, LinkButton)
        Dim s As String = lb.CommandArgument
End Sub

linkbutton正确地添加到网格单元格,但是当你没有触发click事件时。

思考? 谢谢!

1 个答案:

答案 0 :(得分:1)

您不应在DataGrid的ItemDataBound事件(或GridView的RowDataBound - 事件)中动态添加控件。只有在将DataGrid数据绑定到DataSource时才会触发ItemDataBound。如果您已启用ViewState并仅在Not Page.IsPostback时对其进行数据绑定,则不会在回发时重新创建控件。因此,不会触发任何事件。

您应该使用ItemCreated代替(GridView中的RowCreated)动态创建控件,因为每次回发都会调用ItemCreated