How to Convert DataTable to DataView in Asp.Net C# VB.Net

Sometimes we need to use DataView. Since DataTable is a popular data container developers use DataTable by default. That’s in some cases we need to Convert DataTable to a DataView. Here in this article i will show you how one can easily convert a DataTable to a DataView using both Asp.net C# and VB.Net.

First Add a GridView Like Below:

  <asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
    </asp:GridView>

Now First Create a DataTable then Convert to DataView & Bind to the GridView Control:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable oTable = new DataTable("Article");

            //Add DataTable column dynamically/run time/on the fly.
            oTable.Columns.Add(new DataColumn("ID", typeof(System.Int64)));
            oTable.Columns.Add(new DataColumn("Title", typeof(System.String)));
            oTable.Columns.Add(new DataColumn("Published", typeof(System.DateTime)));

            //Add DataTable rows dynamically/run time/on the fly.
            oTable.Rows.Add(1001, "DataTable Engineering", DateTime.Now);
            oTable.Rows.Add(1002, "Event Calendar", DateTime.Now);
            oTable.Rows.Add(1003, "Master Detail Data", DateTime.Now);

            // Convert DataTable to a DataView
            DataView DV = oTable.DefaultView;

            GridView1.DataSource = DV;
            GridView1.DataBind();
        }
    }

Note: Don’t forget to add “System.Data” namespace.

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim oTable As New DataTable("Article")

            'Add DataTable column dynamically/run time/on the fly.
            oTable.Columns.Add(New DataColumn("ID", GetType(System.Int64)))
            oTable.Columns.Add(New DataColumn("Title", GetType(System.String)))
            oTable.Columns.Add(New DataColumn("Published", GetType(System.DateTime)))

            'Add DataTable rows dynamically/run time/on the fly.
            oTable.Rows.Add(1001, "DataTable Engineering", DateTime.Now)
            oTable.Rows.Add(1002, "Event Calendar", DateTime.Now)
            oTable.Rows.Add(1003, "Master Detail Data", DateTime.Now)

            ' Convert DataTable to a DataView
            Dim DV As DataView = oTable.DefaultView

            GridView1.DataSource = DV
            GridView1.DataBind()
        End If

    End Sub

Note: Don’t forget to add “System.Data” namespace.

Output:
Convert DataTable to DataView

Download Code Example C#        Download Code Example VB.Net

Leave a Reply

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

AlphaOmega Captcha Classica  –  Enter Security Code