Tuesday 22 January 2013

Show checkbox Checked item(s) from one Grid view to another Grid view in ASP.NET

How to Show Data from one grid view to another grid view

Here is the Default.aspx(Source Code):

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace LinqToXML
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SqlConnection con = new SqlConnection("Data Source=DIPTIRANJAN-PC;Initial Catalog=CarProduct;
                                                       User ID=sa;Password=123");
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT * FROM CAR1", con);
                SqlDataAdapter ad = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                ad.Fill(ds);
                DataTable dt1 = ds.Tables[0];
                ViewState["dt1"] = dt1;
                GridView1.DataSource = dt1;
                GridView1.DataBind();
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            DataTable dt1 = (DataTable)ViewState["dt1"];
            DataTable dt2 = dt1.Clone();
            foreach (GridViewRow row in GridView1.Rows)
            {
                if (((CheckBox)row.FindControl("CheckBox1")).Checked)
                {
                    DataRow row1 = dt2.NewRow();
                    foreach (DataRow row2 in dt1.Rows)
                    {
                        if (row2["Id"].ToString() == GridView1.DataKeys[row.DataItemIndex].Value.ToString())
                        {
                            row1["ID"] = row2["ID"];
                            row1["NAME"] = row2["NAME"];
                            row1["PRICE"] = row2["PRICE"];
                            row1["IMAGE"] = row2["IMAGE"];
                            row1["OILType"] = row2["OILType"];
                            row1["Mileage"] = row2["MIleage"];
                            dt2.Rows.Add(row1);
                        }
                    }
                }
            }
            GridView2.DataSource = dt2;
            GridView2.DataBind();
        }
    }
}
OUTPUT: