user194076
user194076

Reputation: 9017

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. 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?

Upvotes: 0

Views: 3139

Answers (1)

agent-j
agent-j

Reputation: 27913

Unless I am mistaken, you create a new DataTable every time a user hits the page.

You need to persist the row to a real database or perhaps make your DataTable shared (static in C#) instead.

Shared dt As DataTable = New DataTable()

Upvotes: 1

Related Questions