How to Cast Gridview to a Data Table

A GridView uses a .NET "DataTable" to populate the GridView's records. To cast the GridView control back to a DataTable, you must recreate the table structure, copy the records to an array, and then assign the array to the DataTable. If you try to directly assign a DataTable to the GridView's records, your .NET Web application displays an error.

Instructions

    • 1

      Click the Windows "Start" button and type "visual studio" in the search text box. Press "Enter" to open the .NET programming software.

    • 2

      Double-click the .NET code file that contains your GridView procedures. Start the code by assigning the GridView's record view to a new DataView control. The following code shows you how to assign the view to a new variable:

      DataView view;

      view = (DataView)grid.Select(DataSourceSelectArguments.Empty);

      Replace "grid" with the name of your own GridView control.

    • 3

      Clone the GridView's structure and assign the structure to a DataTable variable. The following code shows you how to clone the GridView:

      DataTable table;

      table = view.Table.Clone();

    • 4

      Transfer the GridView's records to an array. The array variable automatically parses the records into an array of values. Use the following code to transfer the data:

      GridViewRow[] gridarray = new GridViewRow[grid.Rows.Count];

      grid.Rows.CopyTo(gridarray, 0)

    • 5

      Loop through each array value and assign the values to the DataTable. After you loop through each value, the GridView is finally cast to the DataTable variable. The following code shows you how to loop through the records:

      foreach (GridViewRow row in gridarray)

      {

      DataRow row;

      row= table.NewRow();

      for (int i = 0; i < rows.Cells.Count; i++)

      {

      row[i] = rows.Cells[i].Text;

      }

      table.Rows.Add(row);

      }

Related Searches:

References

Comments

Related Ads

Featured