Drag and Drop GridView Row to DetailsView using jQuery

In this post, I am going to explain with a simple example on how to drag a GridView row and drop it in a DetailsView using jQuery UI's 'Draggable' and 'Droppable' mouse interactions. 


Before we start implementing this, it is better to have a knowledge on what jQuery UI's draggable and droppable interaction feature provide. You can see live demonstrations in the links provided in the previous sentence. Draggable feature enables dragging functionality on any DOM element and Droppable feature make the element accept the dragged element to be dropped in it. This is very simple and you need not be a jQuery scholar to understand this example.

Steps to Reproduce


1. Create a MySql table with the following structure and populate it with dummy data. This data will be used to populate the gridview. You can also use other databases but make sure to correct the connection strings in the code below while populating gridview.

+-------------+-------------+
| Field       | Type        |
+-------------+-------------+
| id          | int(11)     | 
| name        | varchar(20) |
| designation | varchar(20) |
| salary      | varchar(20) |
+-------------+-------------+


2. Download latest versions of jQuery and jQuery UI libraries. Add a folder called 'js' to your project and add 'jquery-x.x.x-min.js' and 'jqueryui-x.x.x-min.js' libraries to the js folder you just created.

3. Add a web form to the project, copy and paste the below code in it.


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 
<style type="text/css">
.grd1-header
{   
background-color:Maroon;
border: 3px solid #ffba00;
color:White;
}
.grd2-header
{   
background-color:Green;
border: 3px solid #ffba00;
color:White;
}
.sel-row
{   
background-color:Yellow;
border: 3px solid #ffba00;
color:Black;
}
.sel-row td
{
cursor:move;
font-weight:bold;
}
</style>
    <title>Drag & Drop GridView</title>
    <script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
    <script src="js/jquery-ui-1.8.24.custom.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var droppedItemIndex = -1;
            $('.block').draggable({
                helper: "clone",
                cursor: "move"
            });
            $('#<%=DetailsView1.ClientID %>').droppable({
                drop: function (ev, ui) {
                    accept: '.block',
                     droppedItemIndex = $(ui.draggable).index(); 
                    var droppedItem = $(".grd-source tr").eq(droppedItemIndex);
                    index = -1;
                    $("[id*=DetailsView1] .name").html(droppedItem.find(".name").html());
                    $("[id*=DetailsView1] .designation").html(droppedItem.find(".designation").html());

                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <h1>Drag and Drop GridView Row to another GridView using jQuery</h1>
    <div>
    <table class="ui-corner-top" border="1">
    <tr>
    <td>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"  
            onrowcreated="GridView1_RowCreated" CssClass="grd-source" >
            <SelectedRowStyle CssClass="block sel-row" />
            <RowStyle CssClass="block" />
            <HeaderStyle CssClass="grd1-header" />
            <Columns>
            <asp:BoundField DataField="id" HeaderText="ID" ItemStyle-CssClass="id" />
            <asp:BoundField DataField="name" HeaderText="NAME" ItemStyle-CssClass="name" />
             <asp:BoundField DataField="designation" HeaderText="DESIGNATION" ItemStyle-CssClass="designation" />
              <asp:BoundField DataField="salary" HeaderText="SALARY" ItemStyle-CssClass="salary" />
           </Columns>
        </asp:GridView>
    </td>
    <td valign="middle">
         <asp:DetailsView CssClass="ui-widget" ID="DetailsView1" runat="server"
        Height="50px" Width="125px" AutoGenerateRows="false">
        <Fields> 
          <asp:BoundField DataField="name" HeaderText="Name" ItemStyle-CssClass="name" />
          <asp:BoundField DataField="designation" HeaderText="Designation" ItemStyle-CssClass="designation" />
        </Fields>
         <HeaderStyle BackColor="Green" ForeColor="White" HorizontalAlign="Center" />  
            <HeaderTemplate>  
                <asp:Label ID="Label1" runat="server" Text="Details" Font-Size="Large"></asp:Label>  
            </HeaderTemplate> 
    </asp:DetailsView>
    </td>
    </tr>
</table>   
    </div>
    </form>
</body>
</html>

3. In the code-behind page add the following code.


protected void Page_Load(object sender, EventArgs e)
        {
            //Fetch data from mysql database
            MySqlConnection conn = new MySqlConnection("server=localhost;uid=root;password=priya123;database=test; pooling=false;");
            conn.Open();
            string cmd = "select * from employee";
            MySqlDataAdapter dAdapter = new MySqlDataAdapter(cmd, conn);
            DataSet objDs = new DataSet();
            dAdapter.Fill(objDs);
            GridView1.DataSource= objDs.Tables[0];
            GridView1.DataBind();
            DataTable dt = new DataTable();
            objDs.Tables[0].Clear();
            dt = objDs.Tables[0];
            dt.Rows.Add();
            DetailsView1.DataSource = dt;
            DetailsView1.DataBind();
            
        }


        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "this.className='block sel-row'");
                e.Row.Attributes.Add("onmouseout", "this.className='block'");
            }
        }

4. Now build the project and run it. You will now be able to drag a row from gridview and drop it in the details view as shown below.


Code Explanation

As I mentioned earlier, draggable feature can be enabled on any DOM element. In the above code, each gridview row (typically an HTML table row tr) is assigned a css class named ".block" and using this css class we are enabling draggable option on each grid view row. 

$('.block').draggable({
                helper: "clone",
                cursor: "move"
            });

The helper option with value 'clone' makes a copy of gridview and does not move the gridview row itself to the detailsview. Same way droppable option is enabled on the DetailsView with the below code.

$('#<%=DetailsView1.ClientID %>').droppable({
                drop: function (ev, ui) {
                    accept: '.block',
                     droppedItemIndex = $(ui.draggable).index(); 
                    var droppedItem = $(".grd-source tr").eq(droppedItemIndex);
                    index = -1;
                    $("[id*=DetailsView1] .name").html(droppedItem.find(".name").html());
                    $("[id*=DetailsView1] .designation").html(droppedItem.find(".designation").html());

                }
            });

Here, we define what should be done whenever an object is dropped on to the detailsview inside the drop method. The first option, accept:'.block' restricts the detailsview to accept elements with .block css class alone. Then we identify the index of the dropped element, in this case the index of the gridview row that is being dropped, using the index() method. Finally we get the corresponding row values and place it in the appropriate fields of details view.

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *