Hi georgeacuster...,
Please refer below sample.
HTML
<asp:GridView runat="server" ID="gvCustomers" AutoGenerateColumns="false"
OnSelectedIndexChanged="OnSelectedIndexChanged">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
<asp:ButtonField Text="Select" CommandName="Select" ButtonType="Button" />
</Columns>
</asp:GridView>
<br />
<asp:Button Text="Copy" runat="server" OnClick="Copy" />
Namespaces
C#
using System.Data;
using System.Drawing;
VB.Net
Imports System.Data
Imports System.Drawing
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
if (ViewState["Customers"] == null)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]
{
new DataColumn("CustomerId", typeof(int)),
new DataColumn("Name"),
new DataColumn("Country")
});
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
ViewState["Customers"] = dt;
}
this.gvCustomers.DataSource = ViewState["Customers"] as DataTable;
this.gvCustomers.DataBind();
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
this.gvCustomers.SelectedRow.BackColor = Color.Cyan;
}
protected void Copy(object sender, EventArgs e)
{
GridViewRow gvRow = this.gvCustomers.SelectedRow;
DataTable dt = null;
if (ViewState["Customers"] != null)
{
dt = ViewState["Customers"] as DataTable;
dt.Rows.Add(gvRow.Cells[0].Text, gvRow.Cells[1].Text, gvRow.Cells[2].Text);
ViewState["Customers"] = dt;
}
this.BindGrid();
}
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()
If ViewState("Customers") Is Nothing Then
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn() {New DataColumn("CustomerId", GetType(Integer)), New DataColumn("Name"), New DataColumn("Country")})
dt.Rows.Add(1, "John Hammond", "United States")
dt.Rows.Add(2, "Mudassar Khan", "India")
dt.Rows.Add(3, "Suzanne Mathews", "France")
dt.Rows.Add(4, "Robert Schidner", "Russia")
ViewState("Customers") = dt
End If
Me.gvCustomers.DataSource = TryCast(ViewState("Customers"), DataTable)
Me.gvCustomers.DataBind()
End Sub
Protected Sub OnSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Me.gvCustomers.SelectedRow.BackColor = Color.Cyan
End Sub
Protected Sub Copy(ByVal sender As Object, ByVal e As EventArgs)
Dim gvRow As GridViewRow = Me.gvCustomers.SelectedRow
Dim dt As DataTable = Nothing
If ViewState("Customers") IsNot Nothing Then
dt = TryCast(ViewState("Customers"), DataTable)
dt.Rows.Add(gvRow.Cells(0).Text, gvRow.Cells(1).Text, gvRow.Cells(2).Text)
ViewState("Customers") = dt
End If
Me.BindGrid()
End Sub
Screenshot