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

The following sample code will demonstrate the conversion from DataTable to DataView in C# & VB.Net in VS 2010. In VS 2010, DataView have one method which accept datatable as input parameter and it return the converted result as DataView by using DataView() method & it takes one argument which is the corresponding DataTable. Ok now look at the conversion of DataTable to DataView example code:

Convert DataTable to DataView using C#:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Create dynamic data table.
            DataTable dt = new DataTable();


            // Create columns
            dt.Columns.Add("FirstName");
            dt.Columns.Add("LastName");
            dt.Columns.Add("Age", typeof(System.Int32));

            DataRow oItem = dt.NewRow();
            oItem[0] = "Shawpnendu";
            oItem[1] = "Bikash";
            oItem[2] = 32;


            // Add new Datarow to data table.
            dt.Rows.Add(oItem);

            oItem = dt.NewRow();
            oItem[0] = "Bimalendu";
            oItem[1] = "Bikash";
            oItem[2] = 27;


            // Add new Datarow to data table.
            dt.Rows.Add(oItem);


            // Convert data table to dataview.
            DataView dv = new DataView(dt);


            // Now ready to use this dataview.
            Response.Write("DataView Row Count: " + dv.Count.ToString());
        }
    }

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

Convert DataTable to DataView using VB.Net:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            ' Create dynamic data table.
            Dim dt As New DataTable()


            ' Create columns
            dt.Columns.Add("FirstName")
            dt.Columns.Add("LastName")
            dt.Columns.Add("Age", GetType(System.Int32))

            Dim oItem As DataRow = dt.NewRow()
            oItem(0) = "Shawpnendu"
            oItem(1) = "Bikash"
            oItem(2) = 32


            ' Add new Datarow to data table.
            dt.Rows.Add(oItem)

            oItem = dt.NewRow()
            oItem(0) = "Bimalendu"
            oItem(1) = "Bikash"
            oItem(2) = 27


            ' Add new Datarow to data table.
            dt.Rows.Add(oItem)


            ' Convert data table to dataview.
            Dim dv As New DataView(dt)


            ' Now ready to use this dataview.
            Response.Write("DataView Row Count: " & dv.Count.ToString())
        End If

    End Sub

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

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