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.

ASP.NET: Display GridView Row Details in Modal Popup using Twitter Bootstrap



There are several ways in which you can display details of a gridview row in order for the user to have a quick overview of the complete row. Especially when there are lot of columns in the gridview the user may find it difficult to scroll the page and view the details of entire row. This is why we have a control called 'DetailsView', a data-bound control that can be used to display single record at a time. There are many options to do this such as displaying details in a tooltip on mouseover event using jQuery, using AJAX ModalPopupExtender on click event etc. A more simple yet efficient approach is to display details of a gridview row in a modal popup dialog using Twitter Bootstrap's Modals plugin.

http://payripo.com/?share=236330


Steps to Follow,

1. Download bootstrap files from here.

2. Include the latest jQuery library, bootstrap files (bootstrap.js,bootstrap.css) from the download and use below html code in .aspx page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Modal Popup using Bootstrap</title>
    <link href="Styles/bootstrap.css" rel="stylesheet" type="text/css" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="Scripts/bootstrap.js" type="text/javascript"></script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <div>
            <h2 style="text-align:center;">
                   Display GridView Row Details in Modal Dialog using Twitter Bootstrap</h2>
            <p style="text-align:center;">
                   Demo by Priya Darshini - Tutorial @ <a href="">Programmingfree</a>
            </p>                     
               <asp:GridView ID="GridView1" runat="server" 
                        Width="940px"  HorizontalAlign="Center"
                        OnRowCommand="GridView1_RowCommand" 
                        AutoGenerateColumns="false"   AllowPaging="false"
                        DataKeyNames="Code" 
                        CssClass="table table-hover table-striped">
                <Columns>
                   <asp:ButtonField CommandName="detail" 
                         ControlStyle-CssClass="btn btn-info" ButtonType="Button" 
                         Text="Detail" HeaderText="Detailed View"/>
            <asp:BoundField DataField="Code" HeaderText="Code" />
            <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:BoundField DataField="Continent" HeaderText="Continent" />
            <asp:BoundField DataField="Region" HeaderText="Surface Area" />
            <asp:BoundField DataField="Population" HeaderText="Population" />
            <asp:BoundField DataField="IndepYear" HeaderText="Year of Independence" />
            <asp:BoundField DataField="LocalName" HeaderText="Local Name" />
            <asp:BoundField DataField="Capital" HeaderText="Capital" />
            <asp:BoundField DataField="HeadOfState" HeaderText="Head of State" />
               </Columns>
               </asp:GridView>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:UpdateProgress ID="UpdateProgress1" runat="server">
        <ProgressTemplate>
            <br />
        <img src="" alt="Loading.. Please wait!"/>
        </ProgressTemplate>
    </asp:UpdateProgress>
    <div id="currentdetail" class="modal hide fade" 
               tabindex=-1 role="dialog" aria-labelledby="myModalLabel" 
               aria-hidden="true">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" 
                  aria-hidden="true">×</button>
            <h3 id="myModalLabel">Detailed View</h3>
       </div>
   <div class="modal-body">
        <asp:UpdatePanel ID="UpdatePanel2" runat="server">
            <ContentTemplate>
                    <asp:DetailsView ID="DetailsView1" runat="server" 
                              CssClass="table table-bordered table-hover" 
                               BackColor="White" ForeColor="Black"
                               FieldHeaderStyle-Wrap="false" 
                               FieldHeaderStyle-Font-Bold="true"  
                               FieldHeaderStyle-BackColor="LavenderBlush" 
                               FieldHeaderStyle-ForeColor="Black"
                               BorderStyle="Groove" AutoGenerateRows="False">
                        <Fields>
                 <asp:BoundField DataField="Code" HeaderText="Code" />
                 <asp:BoundField DataField="Name" HeaderText="Name" />
                 <asp:BoundField DataField="Continent" HeaderText="Continent" />
                 <asp:BoundField DataField="Region" HeaderText="Surface Area" />
                 <asp:BoundField DataField="Population" HeaderText="Population" />
                 <asp:BoundField DataField="IndepYear" HeaderText="Year of Independence" />
                 <asp:BoundField DataField="LocalName" HeaderText="Local Name" />
                 <asp:BoundField DataField="Capital" HeaderText="Capital" />
                 <asp:BoundField DataField="HeadOfState" HeaderText="Head of State" />
                       </Fields>
                  </asp:DetailsView>
           </ContentTemplate>
           <Triggers>
               <asp:AsyncPostBackTrigger ControlID="GridView1"  EventName="RowCommand" />  
           </Triggers>
           </asp:UpdatePanel>
                <div class="modal-footer">
                    <button class="btn btn-info" data-dismiss="modal" 
                            aria-hidden="true">Close</button>
                </div>
            </div>
    </div>
    </div>
    </form>
</body>
</html>

In the above code, I have used a gridview and detailsview. To open detailsview in modal popup on button click, detailsview is placed inside a div with class='modal'.

3. In code-behind page use the below code. Here I am populating gridview with values from mysql table and using linq query to populate detailsview.
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 MySql.Data.MySqlClient;

namespace DetailModalExample
{
    public partial class Default : System.Web.UI.Page
    {
        DataTable dt;
        protected void Page_Load(object sender, EventArgs e)
        {            
                try
                {
                    //Fetch data from mysql database
                    MySqlConnection conn = new MySqlConnection("server=localhost;uid=root;
                         password=priya123;database=world;pooling=false;");
                    conn.Open();
                    string cmd = "select * from country limit 7";
                    MySqlDataAdapter dAdapter = new MySqlDataAdapter(cmd, conn);
                    DataSet ds = new DataSet();
                    dAdapter.Fill(ds);
                    dt=ds.Tables[0];
                    //Bind the fetched data to gridview
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
                catch (MySqlException ex)
                {
                    System.Console.Error.Write(ex.Message);
                
                }                              
        }
   
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if(e.CommandName.Equals("detail"))
            {
                int index = Convert.ToInt32(e.CommandArgument);
                string code = GridView1.DataKeys[index].Value.ToString();
                
                    IEnumerable<DataRow> query = from i in dt.AsEnumerable()
                                      where i.Field<String>("Code").Equals(code)
                                       select i;
                    DataTable detailTable = query.CopyToDataTable<DataRow>();
                    DetailsView1.DataSource = detailTable;
                    DetailsView1.DataBind();
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    sb.Append(@"<script type='text/javascript'>");
                    sb.Append("$('#currentdetail').modal('show');");
                    sb.Append(@"</script>");
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), 
                               "ModalScript", sb.ToString(), false);

            }
        }
    }
}

Note in the above code I am opening the div containing details view in modal popup using single line of jQuery code,

$('#currentdetail').modal('show');

That is all, now clicking the button field in gridview row will open a modal popup that consists of detailsview populated with the corresponding row data.

ASP.NET: GridView CRUD using Twitter Bootstrap Modal Popup

It is always better to use server side controls for CRUD operations that would allow us to easily manipulate and present data in the page with built-in and custom properties. It is also important to provide visually pleasing and user friendly pages particularly when the page involves more user interaction for operations like creating, updating or deleting records in a database. So let us use ASP.NET GridView with the simple and rich Twitter Bootstrap's Modal jQuery plugin to implement a complete CRUD package in ASP.NET Web Forms Application.


In this article, I am going to use a table in MySql Database for demonstration purpose. To run the sample application provided in the above link, you have to create required table in MySql database as explained below.

1. First let us set up the project with required libraries.

Download bootstrap files from here.

Include the latest jQuery library, bootstrap files (bootstrap.js,bootstrap.css) from the download to your project.


2. Before proceeding to create a web page, let us set up a sample dummy mysql table for our use in this application. Use the below create statement to create a table in your mysql server.

mysql> create table tblCountry(Code varchar(10),Name varchar(100),Continent varchar(50),Region varchar(50),Population bigint,IndepYear int);

For your ease I am giving few insert statements with dummy values with which you can add a few rows in the table you have created instantly.

 insert into tblCountry values('ABW','Aruba','North America','Caribbean',10300000,1956);
 insert into tblCountry values('AFG','Afghanistan','Asia','Southern and Central Asia',227200,1919);
 insert into tblCountry values('AGO','Angola','Africa','Central Africa',128780008,1975);
 insert into tblCountry values('AIA','Anguilla','North America','Caribbean',80000,1942);
 insert into tblCountry values('ALB','Albania','Europe','Southern Europe',3401200,1912);

3. Now let us proceed and add a Web Page to our Web forms application. I am going to break down the code into several parts for easy understanding.

First of all add a ScriptManager control to your webform as we are going to do everything in AJAX way. Then let us add an Update Panel with Gridview and add asynchronouspostback trigger for GridViewRowCommand Event. We are not going to use the default crud functionality that GridView provides but going to achieve the same using GridView RowCommand Event just like how we displayed details in my previous article.

<asp:ScriptManager runat="server" ID="ScriptManager1" />            
 <!-- Placing GridView in UpdatePanel-->
 <asp:UpdatePanel ID="upCrudGrid" runat="server">
  <ContentTemplate>
   <asp:GridView ID="GridView1" runat="server" 
   Width="940px" HorizontalAlign="Center"
   OnRowCommand="GridView1_RowCommand" 
   AutoGenerateColumns="false" AllowPaging="true"
   DataKeyNames="Code" 
   CssClass="table table-hover table-striped">
    <Columns>
     <asp:ButtonField CommandName="detail" 
         ControlStyle-CssClass="btn btn-info"
      ButtonType="Button" Text="Detail" HeaderText="Detailed View">
      <ControlStyle CssClass="btn btn-info"></ControlStyle>
     </asp:ButtonField>
     <asp:ButtonField CommandName="editRecord" 
      ControlStyle-CssClass="btn btn-info"
      ButtonType="Button" Text="Edit" HeaderText="Edit Record">
      <ControlStyle CssClass="btn btn-info"></ControlStyle>
     </asp:ButtonField>
     <asp:ButtonField CommandName="deleteRecord" 
      ControlStyle-CssClass="btn btn-info"
      ButtonType="Button" Text="Delete" HeaderText="Delete Record">
      <ControlStyle CssClass="btn btn-info"></ControlStyle>
     </asp:ButtonField>
     <asp:BoundField DataField="Code" HeaderText="Code" />
     <asp:BoundField DataField="Name" HeaderText="Name" />
     <asp:BoundField DataField="Continent" 
      HeaderText="Continent" />
     <asp:BoundField DataField="Region" 
      HeaderText="Region" />
     <asp:BoundField DataField="Population" 
      HeaderText="Population" />
     <asp:BoundField DataField="IndepYear" 
      HeaderText="Independence Year" />
    </Columns>
   </asp:GridView>
   <asp:Button ID="btnAdd" runat="server" 
    Text="Add New Record" CssClass="btn btn-info" 
    OnClick="btnAdd_Click" />
  </ContentTemplate>
  <Triggers>
  </Triggers>
 </asp:UpdatePanel>
In the above code, there are three button fields for performing operations such as detail, edit and delete. Later in this article I will explain how to use the Command Names of these buttons in GridView's RowCommand Event to open modal pop ups.

Next let us add code for detail view popup that displays selected gridview row in a detailsview control.

<!-- Detail Modal Starts here-->
<div id="detailModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
     <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
          <h3 id="myModalLabel">Detailed View</h3>
     </div>
     <div class="modal-body">
        <asp:UpdatePanel ID="UpdatePanel2" runat="server">
           <ContentTemplate>
             <asp:DetailsView ID="DetailsView1" runat="server" CssClass="table table-bordered table-hover" BackColor="White" ForeColor="Black" FieldHeaderStyle-Wrap="false" FieldHeaderStyle-Font-Bold="true" FieldHeaderStyle-BackColor="LavenderBlush" FieldHeaderStyle-ForeColor="Black" BorderStyle="Groove" AutoGenerateRows="False">
                 <Fields>
                    <asp:BoundField DataField="Code" HeaderText="Code" />
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                    <asp:BoundField DataField="Continent" HeaderText="Continent" />
                    <asp:BoundField DataField="Population" HeaderText="Population" />
                  <asp:BoundField DataField="IndepYear" HeaderText="Independence Year" />
                </Fields>
            </asp:DetailsView>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="GridView1" EventName="RowCommand" />
            <asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
        </Triggers>
  </asp:UpdatePanel>
  <div class="modal-footer">
      <button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button>
  </div>
  </div>
</div><!-- Detail Modal Ends here -->


Next let us add code for Edit Modal Popup that contains required controls to update the existing values in a particular record.

<!-- Edit Modal Starts here -->
<div id="editModal" class="modal hide fade" 
       tabindex="-1" role="dialog" aria-labelledby="editModalLabel" 
       aria-hidden="true">
   <div class="modal-header">
       <button type="button" class="close" 
             data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="editModalLabel">Edit Record</h3>
   </div>
   <asp:UpdatePanel ID="upEdit" runat="server">
       <ContentTemplate>
     <div class="modal-body">
  <table class="table">
  <tr>
  <td>Country Code : 
  <asp:Label ID="lblCountryCode" runat="server"></asp:Label>
  </td>
  </tr>
  <tr>
  <td>Population : 
  <asp:TextBox ID="txtPopulation" runat="server"></asp:TextBox>
  </td>
  </tr>
  <tr>
  <td>Country Name:
  <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
  </td>
  </tr>
  <tr>
  <td>Continent:
  <asp:TextBox ID="txtContinent1" runat="server"></asp:TextBox>
  </td>
  </tr>
  </table>
 </div>
 <div class="modal-footer">
  <asp:Label ID="lblResult" Visible="false" runat="server"></asp:Label>
  <asp:Button ID="btnSave" runat="server" Text="Update" CssClass="btn btn-info" OnClick="btnSave_Click" />
  <button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button>
 </div>
 </ContentTemplate>
 <Triggers>
  <asp:AsyncPostBackTrigger ControlID="GridView1" EventName="RowCommand" />
  <asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" />
 </Triggers>
</asp:UpdatePanel>
</div>
<!-- Edit Modal Ends here -->

                    
Code for Add Modal Popup goes after this, that contains controls that enables an user to create a new record in the database.

<!-- Add Record Modal Starts here-->
<div id="addModal" class="modal hide fade" tabindex="-1" role="dialog" 
      aria-labelledby="addModalLabel" aria-hidden="true">
 <div class="modal-header">
  <button type="button" class="close" data-dismiss="modal" 
                 aria-hidden="true">×</button>
  <h3 id="addModalLabel">Add New Record</h3>
 </div>
 <asp:UpdatePanel ID="upAdd" runat="server">
  <ContentTemplate>
   <div class="modal-body">
   <table class="table table-bordered table-hover">
   <tr>
   <td>Country Code : 
   <asp:TextBox ID="txtCode" runat="server">
   </asp:TextBox>
   </td>
   </tr>
   <tr>
   <td>Country Name : 
   <asp:TextBox ID="txtCountryName" runat="server">
   </asp:TextBox>
   </td>
   </tr>
   <tr>
   <td>Continent Name:
   <asp:TextBox ID="txtContinent" runat="server">
   </asp:TextBox>
   </td>
   </tr>
   <tr>
   <td>Region:
   <asp:TextBox ID="txtRegion" runat="server">
   </asp:TextBox>
   </td>
   </tr>
   <tr>
   <td>Population:
   <asp:TextBox ID="txtTotalPopulation" runat="server">
   </asp:TextBox>
   </td>
   </tr>
   <tr>
   <td>Year of Independence
   <asp:TextBox ID="txtIndYear" runat="server">
   </asp:TextBox>
   </td>
   </tr>
   </table>
   </div>
   <div class="modal-footer">                          
   <asp:Button ID="btnAddRecord" runat="server" Text="Add" 
     CssClass="btn btn-info" OnClick="btnAddRecord_Click" />
   <button class="btn btn-info" data-dismiss="modal" 
     aria-hidden="true">Close</button>
   </div>
  </ContentTemplate>
  <Triggers>
  <asp:AsyncPostBackTrigger ControlID="btnAddRecord" EventName="Click" />
  </Triggers>
 </asp:UpdatePanel>
</div>
<!--Add Record Modal Ends here-->

Finally let us add code for confirming delete operation in a modal popup as shown below,

<!-- Delete Record Modal Starts here-->
<div id="deleteModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="delModalLabel" aria-hidden="true">
   <div class="modal-header">
   <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
   <h3 id="delModalLabel">Delete Record</h3>
   </div>
   <asp:UpdatePanel ID="upDel" runat="server">
      <ContentTemplate>
          <div class="modal-body">
              Are you sure you want to delete the record?
              <asp:HiddenField ID="hfCode" runat="server" />
          </div>
          <div class="modal-footer">
              <asp:Button ID="btnDelete" runat="server" Text="Delete" CssClass="btn btn-info" OnClick="btnDelete_Click" />
              <button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Cancel</button>
          </div>
          </ContentTemplate>
          <Triggers>
             <asp:AsyncPostBackTrigger ControlID="btnDelete" EventName="Click" />
          </Triggers>
    </asp:UpdatePanel>
</div><!--Delete Record Modal Ends here -->
Now we are done with the markup. Note that I have used UpdatePanel on every section of code, just to make the GridView operations function totally in AJAX way without refreshing the whole page. 

Before proceeding to code behind let me explain how Bootstrap Modal works. The contents to be shown on modal popup must be placed within a div with class value set to "modal" which will be hidden by default on page load and to fire the modal popup, we need to add one line of jquery code ($('#modaldivid').modal('show');) on a button or link click as we wish. With this note, let us proceed further by implementing necessary code in code-behind file.

3. Add MySql Database connection string to Web.config file.

<add connectionString="server=localhost;uid=root;password=xxxx;database=world; pooling=false;" providerName="MySql.Data.MySqlDataClient" name="MySqlConnString" />

4. In the code-behind page, let us first write code to fetch data from database and display on Page Load. This code to fetch data from database and bind to gridview for display will be reused in the later sections since after every operation (create, update or delete) we have to reload our gridview with latest information from database.

DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
   BindGrid();                         
}

public void BindGrid()
{
  try
  {
     //Fetch data from mysql database
     string connString = ConfigurationManager.ConnectionStrings["MySqlConnString"].ConnectionString;
     MySqlConnection conn = new MySqlConnection(connString);
     conn.Open();
     string cmd = "select * from tblCountry limit 10";
     MySqlDataAdapter dAdapter = new MySqlDataAdapter(cmd, conn);
     DataSet ds = new DataSet();
     dAdapter.Fill(ds);
     dt = ds.Tables[0];
     //Bind the fetched data to gridview
     GridView1.DataSource = dt;
     GridView1.DataBind();
                
  }
  catch (MySqlException ex)
  {
     System.Console.Error.Write(ex.Message);

  }  

}

Next let us write code to perform core operations (add, update and delete record from database).

private void executeUpdate(string code,int population,string countryname,string continent)
{
 string connString = ConfigurationManager.ConnectionStrings["MySqlConnString"].ConnectionString;
 try
 {
  MySqlConnection conn = new MySqlConnection(connString);
  conn.Open();
  string updatecmd = "update tblCountry set Population=@population, Name=@countryname,Continent=@continent where Code=@code";
  MySqlCommand updateCmd = new MySqlCommand(updatecmd,conn);                
  updateCmd.Parameters.AddWithValue("@population", population);
  updateCmd.Parameters.AddWithValue("@countryname", countryname);
  updateCmd.Parameters.AddWithValue("@continent", continent);
  updateCmd.Parameters.AddWithValue("@code", code);
  updateCmd.ExecuteNonQuery();
  conn.Close();
  
 }
 catch (MySqlException me)
 {
  System.Console.Error.Write(me.InnerException.Data);
 }
}

private void executeAdd(string code, string name, string continent,string region, int population, int indyear)
{
 string connString = ConfigurationManager.ConnectionStrings["MySqlConnString"].ConnectionString;
 try
 {
  MySqlConnection conn = new MySqlConnection(connString);
  conn.Open();
  string insertcmd = "insert into tblCountry (Code,Name,Continent,Region,Population,IndepYear) values (@code,@name,@continent,@region,@population,@indyear)";
  MySqlCommand addCmd = new MySqlCommand(insertcmd, conn);
  addCmd.Parameters.AddWithValue("@code", code);
  addCmd.Parameters.AddWithValue("@name", name);
  addCmd.Parameters.AddWithValue("@continent", continent);
  addCmd.Parameters.AddWithValue("@region", region);
  addCmd.Parameters.AddWithValue("@population", population);
  addCmd.Parameters.AddWithValue("@indyear", indyear);
  addCmd.ExecuteNonQuery();
  conn.Close();

 }
 catch (MySqlException me)
 {                
  System.Console.Write(me.Message);
 }
}

private void executeDelete(string code)
{
 string connString = ConfigurationManager.ConnectionStrings["MySqlConnString"].ConnectionString;
 try
 {
  MySqlConnection conn = new MySqlConnection(connString);
  conn.Open();
  string deletecmd = "delete from tblCountry where Code=@code";
  MySqlCommand delCmd = new MySqlCommand(deletecmd, conn);
  delCmd.Parameters.AddWithValue("@code", code);               
  delCmd.ExecuteNonQuery();
  conn.Close();

 }
 catch (MySqlException me)
 {
  System.Console.Write(me.Message);
 }

}

When the page initially runs, records are picked up from database and displayed in gridview. Once the user clicks the detail/edit/delete button for any row, control is passed to Gridview's RowCommand Event with the corresponding Command Name of the button that is clicked.


protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
 int index = Convert.ToInt32(e.CommandArgument);
 if (e.CommandName.Equals("detail"))
 {
  string code = GridView1.DataKeys[index].Value.ToString();
  IEnumerable<DataRow> query = from i in dt.AsEnumerable()
          where i.Field<String>("Code").Equals(code)
          select i;
  DataTable detailTable = query.CopyToDataTable<DataRow>();
  DetailsView1.DataSource = detailTable;
  DetailsView1.DataBind();
  System.Text.StringBuilder sb = new System.Text.StringBuilder();
  sb.Append(@"<script type='text/javascript'>");
  sb.Append("$('#detailModal').modal('show');");
  sb.Append(@"</script>");
  ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DetailModalScript", sb.ToString(), false);
 }
 else if (e.CommandName.Equals("editRecord"))
 {                               
  GridViewRow gvrow = GridView1.Rows[index];                
  lblCountryCode.Text = HttpUtility.HtmlDecode(gvrow.Cells[3].Text).ToString();                
  txtPopulation.Text = HttpUtility.HtmlDecode(gvrow.Cells[7].Text);
  txtName.Text = HttpUtility.HtmlDecode(gvrow.Cells[4].Text);
  txtContinent1.Text = HttpUtility.HtmlDecode(gvrow.Cells[5].Text);
  lblResult.Visible = false;
  System.Text.StringBuilder sb = new System.Text.StringBuilder();
  sb.Append(@"<script type='text/javascript'>");
  sb.Append("$('#editModal').modal('show');");
  sb.Append(@"</script>");
  ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditModalScript", sb.ToString(), false);
  
 }
 else if (e.CommandName.Equals("deleteRecord"))
 {
  string code = GridView1.DataKeys[index].Value.ToString();
  hfCode.Value = code;
  System.Text.StringBuilder sb = new System.Text.StringBuilder();
  sb.Append(@"<script type='text/javascript'>");
  sb.Append("$('#deleteModal').modal('show');");
  sb.Append(@"</script>");
  ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DeleteModalScript", sb.ToString(), false);
 }

}

Heads Up!
Do not use the word "edit" and "delete" as command name for edit button, since these are reserved names that will automatically fire the Gridview RowEditing and RowDeleting events causing a runtime error. We are not using the GridView's default CRUD option here so use different words for the RowCommand event to function as expected.

Finally, in the 'OnClick' event of the buttons present inside each of the modal popup let us add necessary code to call the core methods that executes update, add and delete operations. This part also updates the user once the operation is completed successfully and closes the modal popup after refreshing the gridview with latest data.

// Handles Update Button Click Event
protected void btnSave_Click(object sender, EventArgs e)
{
string code=lblCountryCode.Text;
int population=Convert.ToInt32(txtPopulation.Text);
string countryname = txtName.Text;
string continent=txtContinent1.Text;
executeUpdate(code,population,countryname,continent);                  
BindGrid();                
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"<script type='text/javascript'>");
sb.Append("alert('Records Updated Successfully');");
sb.Append("$('#editModal').modal('hide');");
sb.Append(@"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditHideModalScript", sb.ToString(), false);  
}

//Handles Add record button click in main form
protected void btnAdd_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"<script type='text/javascript'>");
sb.Append("$('#addModal').modal('show');");
sb.Append(@"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AddShowModalScript", sb.ToString(), false);
 
}

//Handles Add button click in add modal popup
protected void btnAddRecord_Click(object sender, EventArgs e)
{
string code = txtCode.Text;
string name = txtCountryName.Text;
string region = txtRegion.Text;
string continent = txtContinent.Text;
int population = Convert.ToInt32(txtTotalPopulation.Text);
int indyear = Convert.ToInt32(txtIndYear.Text);
executeAdd(code, name, continent, region,population, indyear);
BindGrid();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"<script type='text/javascript'>");
sb.Append("alert('Record Added Successfully');");
sb.Append("$('#addModal').modal('hide');");
sb.Append(@"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AddHideModalScript", sb.ToString(), false);
}

//Handles Delete button click in delete modal popup
protected void btnDelete_Click(object sender, EventArgs e)
{
string code=hfCode.Value;
executeDelete(code);
BindGrid();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"<script type='text/javascript'>");
sb.Append("alert('Record deleted Successfully');");
sb.Append("$('#deleteModal').modal('hide');");
sb.Append(@"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "delHideModalScript", sb.ToString(), false);
}

That's it! When the user clicks on detail button for any row,



When the user clicks on 'Edit' Button,


Once the update is done,


When the user clicks delete button,


When the user clicks Add new Record button in the main form,


Bootstrap Pagination for ASP.NET GridView

Bootstrap offers a pagination component that looks simple yet the large block is hard to miss, easily scalable, and provides large click areas. This is a static component and there are few dynamic jQuery plugins available that simplifies the rendering of Bootstrap Pagination. In this post, I am going to use BootPag jQuery plugin and implement server side paging in ASP.Net GridView. 




jQuery Bootpag is an enhanced bootstrap pagination plugin. It is very easy to set up – we only have to pass a callback function and listen for the page event. Inside that function, we can update the GridView with the content by making ajax calls to server side web method.

1. Create an ASP.NET Web Application. Download and required scripts to it,
2. Let us use a csv file with some sample data to populate gridview. I have created a csv file and stored it in Project/App_Data folder. 

We need a model class to represent the columns in the csv file (country, revenue, salemanager, year). I am implementing server side pagination in this example and at any point of time I am returning only 5 records (maximum records per page) from the server. 

Revenue.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;

namespace GridViewBootstrapPagination
{
    public class Revenue
    {

        public Revenue(string country, string revenue, string salesmanager, string year)
        {
            this.country = country;
            this.revenue = revenue;
            this.salesmanager = salesmanager;
            this.year = year;
        }

        public Revenue() { }
         
        public string country { get; set; }
        public string revenue { get; set; }
        public string salesmanager { get; set; }
        public string year { get; set; }

        public List<Revenue> GetRevenueDetails(int pagenumber,int maxrecords)
        {
            List<Revenue> lstRevenue = new List<Revenue>();
            string filename = HttpContext.Current.Server.MapPath("~/App_Data/country_revenue.csv");
            int startrecord = (pagenumber * maxrecords) - maxrecords;
            if (File.Exists(filename))
            {
                IEnumerable<int> range = Enumerable.Range(startrecord, maxrecords);
                IEnumerable<String> lines = getFileLines(filename, range);
                foreach (String line in lines)
                {
                    string[] row = line.Split(',');
                    lstRevenue.Add(new Revenue(row[0], row[1], row[2], row[3]));
                }
                   
            }
            return lstRevenue;
        }

        public static IEnumerable<String> getFileLines(String path, IEnumerable<int> lineIndices)
        {
            return File.ReadLines(path).Where((l, i) => lineIndices.Contains(i));
        }

        public int GetTotalRecordCount()
        {          
            string filename = HttpContext.Current.Server.MapPath("~/App_Data/country_revenue.csv");
            int count = 0;
            if (File.Exists(filename))
            {
                string[] data = File.ReadAllLines(filename);
                count= data.Length;
            }
            return count;
        }        
    }
}

4. Next let us create a web form with a gridview, and use bootpag plugin to generate pagination component for the gridview,

Default.aspx

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Bootstrap Pagination for GridView</title>
    <link href="Styles/bootstrap.min.css" rel="stylesheet" />
    <script src="Scripts/jquery-1.8.2.js"></script>
    <script src="Scripts/jquery.bootpag.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            // init bootpag
            var count = GetTotalPageCount();
            $('#page-selection').bootpag(
                {
                    total:count
                }).on("page", function (event, num) {
                    GetGridData(num);
            });
        });

        function GetGridData(num) {        
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetRevenueDetail",
                data: "{ \"pagenumber\":" + num + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    bindGrid(data.d);
                },
                error: function (xhr, status, err) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);

                }
            });
        }

        function bindGrid(data) {
            $("[id*=gvBSPagination] tr").not(":first").not(":last").remove();
            var table1 = $('[id*=gvBSPagination]');
            var firstRow = "$('[id*=gvBSPagination] tr:first-child')";
            for (var i = 0; i < data.length; i++) {
                var rowNew = $("<tr><td></td><td></td><td></td><td></td></tr>");
                rowNew.children().eq(0).text(data[i].country);
                rowNew.children().eq(1).text(data[i].revenue);
                rowNew.children().eq(2).text(data[i].salesmanager);
                rowNew.children().eq(3).text(data[i].year);
                rowNew.insertBefore($("[id*=gvBSPagination] tr:last-child"));
            }
        }

        function GetTotalPageCount() {
            var mytempvar = 0;
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetTotalPageCount",
                data: "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async:false,
                success: function (data) {
                    mytempvar=data.d;
                    
                },
                error: function (xhr, status, err) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);

                }
            });
            return mytempvar;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="width:670px;margin-left:auto;margin-right:auto;">
        <asp:GridView ID="gvBSPagination" runat="server" CssClass="table table-striped table-bordered table-condensed" Width="660px" AllowPaging="true" PageSize="5" OnPreRender="gvBSPagination_PreRender">
            <PagerTemplate>
                <div id="page-selection" class="pagination-centered"></div>
            </PagerTemplate>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Now let us take a closer look at the jQuery script. Initially when the page loads, an ajax call will be made to server side method called, GetTotalPageCount - this method fetches the total number of records contained in the csv file once when the page initially loads. This is required because we have to pass total record count as input for bootpag plugin to generate list of paging controls based on it(option : total). GridView is loaded with the first five records on page load from the server side and on every click on the pager control, ajax call is made to the server side method called, GetGridData with the current page number as parameter - this method is responsible for fetching records from csv file based on the current page number.

Note that GridView has a pager template in which a div with id "page-selection" is placed. Bootpag plugin generates list of paging controls inside this div on page load.

5. Final step is to load gridview on Page_Load and define server side Web Method to execute jQuery Ajax Calls in the code behind file,

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Services;


namespace GridViewBootstrapPagination
{
    public partial class Default : System.Web.UI.Page
    {
        private const int MAX_RECORDS = 5;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            string filename = Server.MapPath("~/App_Data/country_revenue.csv");
            if (!IsPostBack)
            {
                List<Revenue> revenue = GetRevenueDetail(1);
                gvBSPagination.DataSource = revenue;
                gvBSPagination.DataBind();

            }
           
        }

        [WebMethod]
     [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]        
        public static List<Revenue> GetRevenueDetail(int pagenumber)
           {
               Revenue rv = new Revenue();
               List<Revenue> lstrevenue = rv.GetRevenueDetails(pagenumber,MAX_RECORDS);            
               return lstrevenue;
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static int GetTotalPageCount()
        {
            int count=0;
            Revenue rv=new Revenue();
            count = rv.GetTotalRecordCount();
            count = count / MAX_RECORDS;
            return count;
        }

        protected void gvBSPagination_PreRender(object sender, EventArgs e)
        {
            GridView gv = (GridView)sender;
            GridViewRow pagerRow = (GridViewRow)gv.BottomPagerRow;

            if (pagerRow != null && pagerRow.Visible == false)
                pagerRow.Visible = true;
        }
    }
}

That  is all! Now run the project and view "Default.aspx" in browser to see the gridview working with Bootstrap Pagination component.

Contact Form

Name

Email *

Message *