将行添加到绑定到SqlDataSource的Gridview

时间:2013-05-16 20:30:15

标签: asp.net vb.net gridview data-binding sqldatasource

我正在尝试动态地向gridview添加一行,而gridview有一个绑定到它的SqlDataSource。是否可以在数据仍然绑定时添加自定义行?我在vb编码。

1 个答案:

答案 0 :(得分:-1)

您不会将该行添加到gridview中,您可以将新数据添加到其数据源中,然后绑定gridview。数据不需要在您的数据库中,您可以检索数据,然后将其添加到该对象。

Public Class MyWebForm
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim myList = generateNewList()

        myList.Add(New FooBar(4, "Four"))


        GridView1.DataSource = myList
        GridView1.DataBind()

    End Sub

    Private Function generateNewList() As List(Of FooBar)

        Dim mylist As New List(Of FooBar)

        mylist.Add(New FooBar(1, "One"))
        mylist.Add(New FooBar(2, "Two"))
        mylist.Add(New FooBar(3, "Three"))

        Return mylist

    End Function

End Class

Public Class FooBar

    Private Property myID As Integer
    Private Property myName As String

    Public Property id As Integer
        Get
            Return myID
        End Get
        Set(value As Integer)
            myID = value
        End Set
    End Property
    Public Property name As String
        Get
            Return myName
        End Get
        Set(value As String)
            myName = value
        End Set
    End Property


    Public Sub New(id As Integer, name As String)
        myID = id
        myName = name

    End Sub
End Class