Search code examples
vb.netdatatable

How to create a datatable array/series


I want to create datatable array dynamically. according to i number, a table from datagridview will be saved to a datatable (like table1, table2 table3 etc). At another form, if user writes the i number to textbox, datagridview will be filled using the right table (table1, table2...)

But if I declare table(i) as new datatable, I get "Arrays cannot be declared with 'New'" error

If I declare table(i) as datatable, I get "system.nullreferenceexception object reference not set to an instance of an object" error while adding columns

Sub add newtable() 

Dim i As Integer = TextBox1.Text
Dim table(i) As New DataTable   '!

With table(i).Columns
.Add("sample1", Type.GetType("System.String"))
.Add("sample2", Type.GetType("System.String"))
End With

table(i).Rows.Add("a", "b")
table(i).Rows.Add("c", "d")

End sub

then

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

DataGridView1.DataSource = table(i)

End Sub

Solution

  • First, now and forever, turn on Option Strict. Project Properties -> Compile tab. Also for future projects Tools -> Options -> Projects and Solutions -> VB Defaults

    A DataSet is made to hold DataTables. A List(Of DataTable) might be easier to use because you wouldn't have to keep track of the index. If you really need an array then declare it at the Class level. I like to use the plural for names of collections.

    Private tables As DataTable()
    
    Sub addnewtable()
    
        Dim i As Integer = CInt(TextBox1.Text)
        tables(i) = New DataTable
    
        With tables(i).Columns
            .Add("sample1", Type.GetType("System.String"))
            .Add("sample2", Type.GetType("System.String"))
        End With
    
        tables(i).Rows.Add("a", "b")
        tables(i).Rows.Add("c", "d")
    
    End Sub