Creating a Datatable Manually

This sample shows how to create a datatable manually, adding files from a directory (using System.IO), and then binding the datatable to a Gridview

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>
<script language="VB" Runat="server">
    Dim dt As DataTable
    Dim dr As DataRow
	Sub Page_Load(Source as Object, E as EventArgs)
        dt = GetFiles()
        gvFiles.DataSource = dt
        gvFiles.DataBind()
	End Sub
    Public Function GetFiles() As DataTable
        Dim strFilePath = Server.MapPath("\test\")
        Dim DirInfo As New DirectoryInfo(strFilePath)
        Dim Files As FileInfo() = DirInfo.GetFiles()

        Dim myTable As New DataTable
        myTable.Columns.Add("File Name", Type.GetType("System.String"))
        myTable.Columns.Add("Last Write Time", Type.GetType("System.String"))
        Dim i As Integer
        For i = 0 To Files.Length - 1
            Dim Filename As String = Files(i).Name
            Dim sWrite As String = Files(i).LastWriteTime
            Dim myrow As DataRow
            ' create new row
            myrow = myTable.NewRow
            ' add files/write times into cells
            myrow("File Name") = Filename
            myrow("Last Write Time") = sWrite
            myTable.Rows.Add(myrow)
        Next
        Return myTable
    End Function
</script>
<html>
	<head runat="server">
		<meta name="GENERATOR" Content="ASP Express 5.0">
		<title>Untitled</title>
	</head>
	<body>
        <asp:GridView ID="gvFiles" runat="server" Width="432px">
        </asp:GridView>
		</form>
	</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>