Visual Basic: Manually create a datatable and fill it with records

Platform:Visual Basic
Task:Manually create a datatable and fill it with records
Discussion:
You need to create a table using code and fill it with records
Example:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim MyFilesTable As DataTable = CreateFilesDataTable()
        AddFileRecord(MyFilesTable, "MyFile.txt")
        AddFileRecord(MyFilesTable, "AnotherFile.txt")
        FilesDataGridView.DataSource = MyFilesTable
    End Sub

    Public Function CreateFilesDataTable() As DataTable
        'create the Files datatable
        Dim FilesDataTable As New DataTable

        'add a column
        Dim FileNameColumn As New DataColumn
        With FileNameColumn
            .DataType = System.Type.GetType("System.String")
            .Caption = "File"
            .ColumnName = "FileName"
        End With

        'add the columns to the datatable
        FilesDataTable.Columns.Add(FileNameColumn)
        Return FilesDataTable
    End Function

    Public Sub AddFileRecord(ByRef FilesDataTable As DataTable, ByVal FileName As String)
        'add the column to the datatable
        Dim FileRecord As DataRow = FilesDataTable.NewRow
        FileRecord.Item("Filename") = FileName
        FilesDataTable.Rows.Add(FileRecord)
    End Sub
Back to Index