如何使用VB.net为编程创建的gridview添加编辑,更新和取消按钮操作?

时间:2015-05-08 13:42:23

标签: vb.net visual-studio-2010 visual-studio visual-studio-2012 gridview

我试图以编程方式将网格视图添加到我的网页(在Visual Studio 2012中使用VB.net)。我成功创建了一个gridview,并在我的网格中添加了编辑,更新和取消按钮。但我很惊讶地向这些按钮添加了事件命令。如何使这个按钮工作?正确的知道按钮(编辑/更新/删除)动作没有做任何事情。下面是代码...亲切的帮助。请帮我看一下gridview的编辑,更新和取消按钮的代码(以编程方式添加网格视图)。

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click       
   Dim Gv As GridView = New GridView()
   Dim cf As CommandField = New CommandField()
    Dim df As CommandField = New CommandField()
    Dim ef As CommandField = New CommandField()
    cf.ButtonType = ButtonType.Button
    df.ButtonType = ButtonType.Button
    df.ShowCancelButton = True
    cf.ShowEditButton = True
    ef.ShowDeleteButton = True
    Dim dt As DataTable = Me.GetData("SELECT * FROM Table1")
    Gv.Columns.Add(df)  
    Gv.Columns.Add(cf)
    Gv.Columns.Add(ef)
    Gv.DataSource = dt
    Gv.EditIndex = True
    Gv.DataBind()
    Page.Form.Controls.Add(Gv)

    Private Function GetData(query As String) As DataTable
    Dim dt As New DataTable()
    Dim constr As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(query)
            Using sda As New SqlDataAdapter()
                cmd.CommandType = CommandType.Text
                cmd.Connection = con
                sda.SelectCommand = cmd
                sda.Fill(dt)
            End Using
        End Using
        Return dt
    End Using
End Function 

1 个答案:

答案 0 :(得分:0)

您可以使用AddHandler语句动态添加处理程序,如下所示:

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click       
    Dim Gv As GridView = New GridView()
    ' ...
    AddHandler Gv.RowUpdated, AddressOf Gv_RowUpdated
    ' ...
End Sub

Protected Sub Gv_RowUpdated(Sender As Object, e As GridViewUpdatedEventArgs)
    ' ...
End Sub

不幸的是,在ASP.NET中动态添加控件和事件处理程序非常复杂(有关详细信息,请参阅此link)。例如,您必须在每个PostBack上再次添加事件处理程序。

因此,您可能会更好地使用一种解决方案来切换您在设计时放置在WebForm上的GridView的可见性。如果需要添加多个GridView,可以考虑使用每行包含GridView的Repeater控件。