Gridview使用单击按钮添加行[帮助请]

问题描述:

大家好



我创建了一个gridview和2个文本框,我想创建一个按钮,当我点击它时按钮在gridview中创建一行每个textbox.text



问题是,我可以得到带文本的第一行我想要,但我不能得到第二排。它只是取代了第一个



hi everyone

ive created a gridview and 2 textboxes and i want to create a button that when i click on it and the button creates a row in the gridview that with the text of the 2 texboxes anda a cell (collum) for each textbox.text

the problem is that, i can get the the first row with the text i want, but i cant get a second row. it just replaces the 1st

Protected Function FormatDataTable() As DataTable
    Dim dt As DataTable = New DataTable()
    ' Create Columns
    dt.Columns.Add("id", System.Type.GetType("System.String"))
    dt.Columns.Add("text", System.Type.GetType("System.String"))
    Return dt
End Function

Protected Function GetData1() As DataTable
    Dim dt As DataTable = FormatDataTable()
    Dim dr As DataRow

    ' Populate the datatable with your data (put this in appropriate loop)
    dr = dt.NewRow
    dr("id") = TextBox1.Text
    dr("text") = TextBox2.Text
    ' Add the row
    dt.Rows.Add(dr)

    dt.NewRow()
    Return dt
End Function


Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
    GridView1.DataSource = GetData1()
    GridView1.DataBind()
End Sub

您需要缓存该数据表,因此它会记住有多少行。不要每次构建一个包含1行的新数据表,而是执行类似
You need to cache that data table, so it remembers how many rows there are. Instead of building a new data table with 1 row each time, do something like
dt = Session(SessionVariableNameForTable)

的操作。然后添加新行,并使用

. Then add your new row, and cache the result again with

Session(SessionVariableNameForTable) = dt

再次缓存结果,以便下次更改可用。

so the changes are available the next time through.