Tuesday, February 23, 2010

Convert DataTable to DataView in Asp.net C# in VS 2008

The following sample code will demonstrate the convertion from DataTable to DataView in C# in VS 2008.

In VS 2008, DataView have one method which accept datatable as input parameter and it return the converted result as dataview by using DataView(). Ok now look at the converting DataTable to DataView example code:










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());
        }
    }
Look at the code above its self explanatory. So i hope that no need any explanation.

1 comment:

Write your Comment: