Pass (Send) ASP.Net GridView data to another on Button Click using C# and VB.Net

Last Reply 6 months ago By pandeyism

Posted 6 months ago

How to add the gridview data to another gridview using gridview button click?

Posted 6 months ago

Hi SUJAYS,

Refer below sample.

HTML

<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>
<br />
<asp:Button Text="Transfer" runat="server" OnClick="Transfer" />
<br />
<asp:GridView runat="server" ID="GridView2" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>

Namespaces

C#

using System.Data;

VB.Net

Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Country", typeof(string)) });
        dt.Rows.Add(1, "John Hammod", "USA");
        dt.Rows.Add(1, "Mudassar Khan", "India");
        dt.Rows.Add(1, "Robert downy", "France");
        dt.Rows.Add(1, "Suzzain Mathew", "Rusia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
        ViewState["dt"] = dt;
    }
}

protected void Transfer(object sender, EventArgs e)
{
    DataTable dt = ViewState["dt"] as DataTable;
    GridView2.DataSource = dt;
    GridView2.DataBind();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As DataTable = New DataTable()
        dt.Columns.AddRange(New DataColumn() {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Country", GetType(String))})
        dt.Rows.Add(1, "John Hammod", "USA")
        dt.Rows.Add(1, "Mudassar Khan", "India")
        dt.Rows.Add(1, "Robert downy", "France")
        dt.Rows.Add(1, "Suzzain Mathew", "Rusia")
        GridView1.DataSource = dt
        GridView1.DataBind()
        ViewState("dt") = dt
    End If
End Sub

Protected Sub Transfer(ByVal sender As Object, ByVal e As EventArgs)
    Dim dt As DataTable = TryCast(ViewState("dt"), DataTable)
    GridView2.DataSource = dt
    GridView2.DataBind()
End Sub

Screenshot