Drag and Drop GridView Row to DetailsView using jQuery

In my previous post  I explained about how to search and highlight results in GridView. There are many other interesting and useful fe...


In my previous post I explained about how to search and highlight results in GridView. There are many other interesting and useful features that can be added to the default ASP.NET GridView. "Drag & Drop" is one such feature that adds more interaction to the UI. When there are too many columns in the GridView, it is essential to provide a DetailsView for the end user to interpret  individual rows effectively. This is done often on clicking GridView select button. To give a different and interactive user experience, we can enable end users with options to drag any row from GridView and drop it on DetailsView for detailed display. 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 detailsview.



Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts.Thanks for reading!!

Subscribe to GET LATEST ARTICLES!


Related

Trending 1705430373829032676

Post a Comment

  1. thank you alot..it's useful for me..

    ReplyDelete
  2. it's nice but how we can drag more than one row into second gridview

    ReplyDelete
  3. hi friend
    can you give me code for searching on gridview column wise with colour change using jquery only (not write .net code and not connect with database also when searching)

    ReplyDelete
  4. Hi Priya,

    This has just proved to be a very useful pointer for me in a project I'm working on using ASP and JQueryUI Touch Punch for Android/iOS drag/drag in HTML. Just wanted to say thanks for making the effort to document it.

    ReplyDelete
  5. Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have 먹튀검증 Hi. I think I have found you just the right time 먹튀검증

    ReplyDelete
  6. What a nice post! I'm so happy to read this. 안전놀이터모음 What you wrote was very helpful to me. Thank you. Actually, I run a site similar to you. If you have time, could you visit my site? Please leave your comments after reading what I wrote. If you do so, I will actively reflect your opinion. I think it will be a great help to run my site. Have a good day.


    ReplyDelete
  7. That's a really impressive new idea! 메이저토토사이트추천 It touched me a lot. I would love to hear your opinion on my site. Please come to the site I run once and leave a comment. Thank you.


    ReplyDelete
  8. I'm a really fortunate male today. After seeing your writing, I saw such great info and also my expertise increased also additionally. I assume I will certainly have the ability to invest a delighted day in your Deokbook. I wish you have a delighted day also. I will certainly constantly sustain you. just click the following page

    ReplyDelete
  9. very nice post, I’ve been absent for a while, but now I remember why I used to love this blog. homework help services Thank you, l try and check back more often. How frequently you update your website?

    ReplyDelete
  10. Woman Sues After 바카라사이트 Refuses To Hand Over $43M Jackpot

    ReplyDelete
  11. "The search feature on khatrimaza.com.in is efficient. Finding my favorite movies is a breeze."

    ReplyDelete

emo-but-icon
:noprob:
:smile:
:shy:
:trope:
:sneered:
:happy:
:escort:
:rapt:
:love:
:heart:
:angry:
:hate:
:sad:
:sigh:
:disappointed:
:cry:
:fear:
:surprise:
:unbelieve:
:shit:
:like:
:dislike:
:clap:
:cuff:
:fist:
:ok:
:file:
:link:
:place:
:contact:

SUBSCRIBE


Hot in weekRecentComments

Recent

Spring Security 4 for Spring MVC using Spring Data JPA and Spring Boot

I have been writing a series of tutorials on using Spring Security 4 in Spring MVC application starting from the basic in-memory authentication. In this post, I am writing a step by ste...

Spring Security JDBC Authentication with Password Encryption

I published a basic level tutorial on how to implement JDBC Authentication and Authorization using Spring Security last week. There are few best practices to be followed while implementing secur...

Spring Security 4 - Simple JDBC Authentication and Authorization

In one of my articles, I explained with a simple example on how to secure a Spring MVC application using Spring Security and with Spring Boot for setup. I am going to extend the same example to ...

Java String Split with Pipe Character Not Working - Solution

If you are working on Java, you might have run into this issue when you try to split a string based on a pipe character ("|"). It simply won't work. Split method in Java takes regex as an argumen...

Comments

premgreen:

Prem Green offers the best hair colour creme for vibrant, salon-like results at home. Our ammonia-free formula is enriched with herbal extracts that nourish hair while giving it a beautiful, even shad...

Ninja:

A very informative and well-structured blog. I appreciate the clarity and depth of the content.social medi...

SKV:

This was so informative and engaging. Keep up the amazing work!luxury villas in india

SKV:

This was so informative and engaging. Keep up the amazing work!Buy 5 bhk villas in gwalior

We Care India:

I love how practical and well-planned these features are. Keep up the excellent work, you're doing an amazing

item