DBAWebFormsVisual Studio 2005ADO.NET.NET 2.0SQL Server 2005C# 2.0IntermediateDevVisual StudioSQL ServerSQLWindows.NETASP.NETC#
GridView to a DataTable
Convert the current Gridview to a datatable
The Problem
SQL Data source retrieves data from the server and bind it to the Gridview, what if the data you need for some reason "that what I have faced when I needed to bid the chart to grid shown data" is the shown data in the Gridview, the data that the Gridview hold now, here is the method to do so:
Solution
- get the a data view from the SQL data source
- check if the data view is not null
- Set the structure of the table from the SQL data source
- Copy the GridViewRows to an array
- Add the values to the new data table:
DataView dataView;dataView = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
if (ChartDataView != null) {}
DataTable dt;
dt = ChartDataView.Table.Clone();
GridViewRow[] Chartarr = new ridViewRow[GridViewData.Rows.Count];
GridViewData.Rows.CopyTo(Chartarr, 0)
foreach (GridViewRow row in Chartarr)
{
DataRow datarw;
datarw = dt.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
datarw[i] = row.Cells[i].Text;
}
dt.Rows.Add(datarw);
}
The Complete Code
if (ChartDataView != null)
{
DataView dataView;
dataView = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
DataTable dt;
dt = ChartDataView.Table.Clone();
GridViewRow[] Chartarr = new ridViewRow[GridViewData.Rows.Count];
GridViewData.Rows.CopyTo(Chartarr, 0)
foreach (GridViewRow row in Chartarr)
{
DataRow datarw;
datarw = dt.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
datarw[i] = row.Cells[i].Text;
}
dt.Rows.Add(datarw);
}
}