arujdevia says:
dr(Gridview1.Columns(j).HeaderText) = Gridview1.Rows(1).Cells(2).Text
Set from variable i and j.
Check the updated code.
HTML
<asp:GridView ID ="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
<hr />
<asp:Button ID="btnCopy" runat="server" Text="CopyOfGridView" OnClick="OnCopyOfDataTable" />
<hr />
<asp:GridView ID="gvDataTable" runat="server" AutoGenerateColumns="true"></asp:GridView>
Namespaces
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId,Name,Country FROM Customers", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}
}
protected void OnCopyOfDataTable(object sender, EventArgs e)
{
DataTable dt1 = new DataTable();
for (int j = 0; j <= gvCustomers.Columns.Count - 1; j += 1)
{
dt1.Columns.Add(gvCustomers.Columns[j].HeaderText);
}
for (int i = 0; i <= gvCustomers.Rows.Count - 1; i++)
{
dt1.Rows.Add();
for (int j = 0; j <= gvCustomers.Columns.Count - 1; j += 1)
{
dt1.Rows[i][j] = gvCustomers.Rows[i].Cells[j].Text;
}
}
gvDataTable.DataSource = dt1;
gvDataTable.DataBind();
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim constring As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constring)
Using cmd As SqlCommand = New SqlCommand("SELECT CustomerId,Name,Country FROM Customers", con)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Using
End Using
End Using
End Using
End Sub
Protected Sub OnCopyOfDataTable(ByVal sender As Object, ByVal e As EventArgs)
Dim dt1 As DataTable = New DataTable()
For j As Integer = 0 To gvCustomers.Columns.Count - 1 Step 1
dt1.Columns.Add(gvCustomers.Columns(j).HeaderText)
Next
For i As Integer = 0 To gvCustomers.Rows.Count - 1
dt1.Rows.Add()
For j As Integer = 0 To gvCustomers.Columns.Count - 1 Step 1
dt1.Rows(i)(j) = gvCustomers.Rows(i).Cells(j).Text
Next
Next
gvDataTable.DataSource = dt1
gvDataTable.DataBind()
End Sub
Screenshot