Introduction
I have a need to display the data on a gridview on another gridview in a modal (bootstrap). So, I thought why not just bind the datasource of a gridview to another but I found out it will not work.
I searched online for a way out and found out most of the solution suggested storing the datatable for the gridview in a session. I don’t personally like the idea of storing big data in a session because of the overhead, so this is a big no for me.
So, I decided to write this method to help in copying the data on the page gridview to the modal gridview.
VB.NET
Public Shared Sub CopyGridViewToGridView(CopyFrom As GridView, CopyTo As GridView, Optional RemovedColumnsIndexes() As Byte = Nothing) Dim dt As DataTable = New DataTable For i As Byte = 0 To CopyFrom.Columns.Count - 1 If IsNothing(RemovedColumnsIndexes) OrElse Not RemovedColumnsIndexes.Contains(i) Then dt.Columns.Add(CopyFrom.Columns(i).HeaderText) End If Next Dim dRow As DataRow For Each row As GridViewRow In CopyFrom.Rows dRow = dt.NewRow() For i As Byte = 0 To CopyFrom.Columns.Count - 1 If IsNothing(RemovedColumnsIndexes) OrElse Not RemovedColumnsIndexes.Contains(i) Then dRow(CopyFrom.Columns(i).HeaderText) = If(row.Cells(i).HasControls, CType(row.Cells(i).Controls(1), Label).Text, row.Cells(i).Text) End If Next dt.Rows.Add(dRow) Next CopyTo.DataSource = dt CopyTo.DataBind() End Sub
C#
public static void CopyGridViewToGridView(GridView CopyFrom, GridView CopyTo, byte[] RemovedColumnsIndexes = null) { DataTable dt = new DataTable(); for (byte i = 0; i <= CopyFrom.Columns.Count - 1; i++) { if (RemovedColumnsIndexes == null || !RemovedColumnsIndexes.Contains(i)) dt.Columns.Add(CopyFrom.Columns[i].HeaderText); } DataRow dRow; foreach (GridViewRow row in CopyFrom.Rows) { dRow = dt.NewRow(); for (byte i = 0; i <= CopyFrom.Columns.Count - 1; i++) { if (RemovedColumnsIndexes == null || !RemovedColumnsIndexes.Contains(i)) dRow[CopyFrom.Columns[i].HeaderText] = row.Cells[i].HasControls() ? ((Label)row.Cells[i].Controls[1]).Text : row.Cells[i].Text; } dt.Rows.Add(dRow); } CopyTo.DataSource = dt; CopyTo.DataBind(); }