简体   繁体   English

如何在数据表中添加行?

[英]How to add a row to a datatable?

I face a stupid problem here. 我在这里面临一个愚蠢的问题。 Cannot find an error and do not really know how to fix this. 找不到错误,也不知道如何解决。

I'm adding an item into datatable on selected index changed. 我在选定索引已更改的数据表中添加了一项。 Everything works, except only the last item is shown in dt. 一切正常,除了dt中仅显示最后一项。 I always has the latest item and all others are gone. 我总是有最新的物品,其他所有物品都不见了。 i suppose this is because I initialize it in the wrong place but still cannot find a solution. 我想这是因为我在错误的地方初始化了它,但仍然找不到解决方案。

 Dim dt As DataTable = New DataTable()
   Protected Sub Page_Load(sender As Object, e As System.EventArgs)   Handles Page.Load
        dt.Columns.Add("dr1")
        dt.Columns.Add("dr2")
    End Sub
Protected Sub ddlTest_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ddlTest.SelectedIndexChanged
            Dim row As DataRow = dt.NewRow()
            row(0) = "Test!"
            row(1) ="Test"
            dt.Rows.Add(row)
        End If
    End Sub

This always shows only last item in list. 它始终仅显示列表中的最后一项。 How do I do this correct way? 我该怎么做正确的方法?

Unless I am mistaken, you create a new DataTable every time a user hits the page. 除非我没有记错,否则每次用户访问页面时都会创建一个新的DataTable。

You need to persist the row to a real database or perhaps make your DataTable shared (static in C#) instead. 您需要将该行持久保存到真实数据库中,或者使您的DataTable共享(在C#中为静态)。

Shared dt As DataTable = New DataTable()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM