Move rows from one Gridview to another in ASP.Net

Mohammed Imtiyaz Jan 22, 2015

Demo

Move Gridview rows from one Gridview to another in ASP.Net

This tutorial will explain you how to move gridview rows from one Gridview to another in ASP.Net using C# and Vb.net

In this tutorial, we will take two Gridviews. The first Gridview contains the list of fruits from which we need to select the fruits along with the quantity of fruits and move them to second gridview and vice versa

We need the following ASP.Net Controls to accomplish this task

  • asp:Gridview
  • asp:ImageButton

Working with the example

Step 1

Create a database “db_moveGridviewRowsFromOneGridviewToAnother”. You can find the Database Script file in Database Folder. Just execute that file; the database will be automatically created.

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="VC.aspx.cs" Inherits="_VC" %>
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
      <title>Move Gridview rows from one Gridview to another in ASP.Net</title>
   </head>
   <body>
      <form id="form1" runat="server">
         <asp:Label ID="lblMsg" runat="server" CssClass="text-danger" Text=""></asp:Label>
         <br />
         <div class="row">
            <div class="col-md-5">
               <asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="False" DataKeyNames="fruit_id" EmptyDataText="GridView1 is empty" CssClass="table table-bordered">
                  <Columns>
                     <asp:TemplateField>
                        <ItemTemplate>
                           <asp:CheckBox ID="chk" runat="server" />
                        </ItemTemplate>
                     </asp:TemplateField>
                     <asp:TemplateField HeaderText="Fruit Name">
                        <ItemTemplate>
                           <asp:Label ID="lblFruitName" runat="server" Text='<%# Bind("fruit_name") %>'></asp:Label>
                        </ItemTemplate>
                     </asp:TemplateField>
                     <asp:TemplateField HeaderText="Qty">
                        <ItemTemplate>
                           <asp:TextBox ID="txtQty" runat="server" Text='<%# Bind("qty") %>' CssClass="form-control" Width="50px"></asp:TextBox>
                        </ItemTemplate>
                     </asp:TemplateField>
                  </Columns>
               </asp:GridView>
            </div>
         </div>
         <div class="row">
            <div class="col-md-5">
               <asp:Button ID="btnMoveDown" runat="server" Text="Move Down" OnClick="btnMoveDown_Click" CssClass="button" />
               <asp:Button ID="btnMoveUp" runat="server" Text="Move Up" OnClick="btnMoveUp_Click" CssClass="button" />
            </div>
         </div>
         <div class="row">
            <div class="col-md-5">
               <asp:GridView ID="GridView2" runat="server" Width="100%" AutoGenerateColumns="false" DataKeyNames="fruit_id" EmptyDataText="GridView1 is empty" CssClass="table table-bordered">
                  <Columns>
                     <asp:TemplateField>
                        <ItemTemplate>
                           <asp:CheckBox ID="chk" runat="server" />
                        </ItemTemplate>
                     </asp:TemplateField>
                     <asp:TemplateField HeaderText="Fruit Name">
                        <ItemTemplate>
                           <asp:Label ID="lblFruitName" runat="server" Text='<%# Bind("fruit_name") %>'></asp:Label>
                        </ItemTemplate>
                     </asp:TemplateField>
                     <asp:TemplateField HeaderText="Qty">
                        <ItemTemplate>
                           <asp:Label ID="Label1" runat="server" Text='<%# Bind("qty") %>'></asp:Label>
                        </ItemTemplate>
                     </asp:TemplateField>
                  </Columns>
               </asp:GridView>
            </div>
         </div>
      </form>
   </body>
</html>

C#

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data; // DataTable
using System.Data.SqlClient; // SQLDataSource
using System.Configuration; // Configuration

public partial class _VC: System.Web.UI.Page
{
    SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["CONN"]);
    DataTable dtFirst, dtSecond;
  
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindFirstGrid();
            GridView2.DataSource = dtSecond;
            GridView2.DataBind();
        }
    }

    public void bindFirstGrid()
    {
        string strQuery = "SELECT fruit_id, fruit_name, '0' AS 'qty' FROM tbl_fruit";
        SqlDataAdapter objDa = new SqlDataAdapter(strQuery, objConn);
        DataSet ds = new DataSet();
        objDa.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        dtFirst = ds.Tables[0];
        dtSecond = dtFirst.Clone();
        ViewState["dtFirst"] = dtFirst;
        ViewState["dtSecond"] = dtSecond;
    }

    protected void btnMoveDown_Click(object sender, EventArgs e)
    {
        dtFirst = (DataTable) ViewState["dtFirst"];
        dtSecond = (DataTable) ViewState["dtSecond"];
        int tmp = 0;
        foreach(GridViewRow gvRow in GridView1.Rows)
        {
            if (((CheckBox) gvRow.FindControl("chk")).Checked)
            {
                dtSecond.Rows.Add(GridView1.DataKeys[gvRow.DataItemIndex].Value, ((Label) gvRow.FindControl("lblFruitName")).Text, ((TextBox) gvRow.FindControl("txtQty")).Text);
                dtFirst.Rows.RemoveAt(gvRow.DataItemIndex - tmp);
                tmp++;
            }
        }
        if (tmp == 0)
            lblMsg.Text = "Please select any row to move down";
        else
        {
            lblMsg.Text = String.Empty;
            GridView2.DataSource = dtSecond;
            GridView2.DataBind();            
            GridView1.DataSource = dtFirst;
            GridView1.DataBind();
            ViewState["dtFirst"] = dtFirst;
            ViewState["dtSecond"] = dtSecond;
        }
    }

    protected void btnMoveUp_Click(object sender, EventArgs e)
    {
        dtFirst = (DataTable) ViewState["dtFirst"];
        dtSecond = (DataTable) ViewState["dtSecond"];
        int tmp = 0;
      
        foreach(GridViewRow gvRow in GridView2.Rows)
        {
            if (((CheckBox) gvRow.FindControl("chk")).Checked)
            {
                dtFirst.Rows.Add(GridView2.DataKeys[gvRow.DataItemIndex].Value, ((Label) gvRow.FindControl("lblFruitName")).Text, "0");
                dtSecond.Rows.RemoveAt(gvRow.DataItemIndex - tmp);
                tmp++;
            }
        }
        if (tmp == 0)
            lblMsg.Text = "Please select any row to move up";
        else
        {
            lblMsg.Text = String.Empty;
            GridView2.DataSource = dtSecond;
            GridView2.DataBind();
            GridView1.DataSource = dtFirst;
            GridView1.DataBind();
            ViewState["dtFirst"] = dtFirst;
            ViewState["dtSecond"] = dtSecond;
        }
    }
}