I am Raghuveer

In my opinion programming means thinking, and it is fun. My vision is to teach programming in more understandable manner to the students from rural background. I support programming for everyone

Showing posts with label GridView. Show all posts
Showing posts with label GridView. Show all posts

Sorting ASP.NET GridView Control using JQuery Tablesorter Plugin

Displaying records in a tabular format is very common functionality of modern websites. Almost all the websites you visit these days have data to display in a table or datagrid and most of them also required the functionality of sorting records based on any column. Last week I had a chance to work with one of a popular JQuery plugin called Tablesorter and I was so impressed that I decided to write a full tutorial on it. In this tutorial, I will show you how you can use JQuery Tablesorter plugin with ASP.NET GridView control to provide client side sorting functionality to your site visitors.
Sorting ASP.NET GridView Control with JQuery Tablesorter Plugin
If you want to play with the Tablesorter JQuery plugin yourself with all the customized options, make sure you download the latest version ofTablesorter plugin from the following URL.
http://tablesorter.com/docs
Create a new ASP.NET website and drag a GridView control on the page. Disable the automatic columns generation by usingAutoGenerateColumns property and add some bound fields inside the GridView Columns collection. For this tutorial, make sure your GridView control HTML markup looks similar to the following:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="Horizontal" Font-Size="9pt" Font-Names="Arial"
AutoGenerateColumns="False" BorderColor="#dadada"
BorderStyle="Solid" BorderWidth="1px">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"
ItemStyle-Width="40" />
<asp:BoundField DataField="Name" HeaderText="Name"
ItemStyle-Width="80" />
<asp:BoundField DataField="Fee" DataFormatString="{0:n0}" HeaderText="Fee"
ItemStyle-Width="60" />
<asp:BoundField DataField="Price" DataFormatString="{0:c}"
HeaderText="Price" ItemStyle-Width="60" />
<asp:BoundField DataField="Discount" DataFormatString="{0:p1}"
HeaderText="Discount" ItemStyle-Width="70" />
<asp:BoundField DataField="Difference" DataFormatString="{0:n1}"
HeaderText="Difference" ItemStyle-Width="80" />
<asp:BoundField DataField="Date" DataFormatString="{0:MMM dd, yyyy}"
HeaderText="Date" ItemStyle-Width="100" />
<asp:BoundField DataField="OnSale" HeaderText="OnSale"
ItemStyle-Width="60" />
</Columns>
</asp:GridView>
As you can see bound fields are bound with columns such as ID, Name, Fee and so on. These columns are coming from a temporary DataTable object which I have filled and bind with GridView in the Page Load event. Following code shows the Page Load event and the code required to fill DataTable.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
int[] ids = {12, 13, 14, 15, 16};
string[] names = {"Alice", "James", "Peter", "Simon", "David"};
int[] fee = { 2299, 5123, 7564, 9595, 1600 };
decimal[] prices = { 12.99m, 122.23m, 25.64m, 66.85m, 1.60m };
decimal[] discounts = { 0.2m, 0.194m, 0.4564m, 0.209m, 0.310m };
decimal[] differences = { -12m, 19.4m, -45.64m, 200.9m, 41.60m };
string[] dates = { "04-12-2010", "07-23-2010", "07-14-2009", "12-12-2010", "11-03-2019" };
bool[] onSale = { true, false, true, true, false };
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(System.Int32));
table.Columns.Add("Name", typeof(System.String));
table.Columns.Add("Fee", typeof(System.Decimal));
table.Columns.Add("Price", typeof(System.Decimal));
table.Columns.Add("Discount", typeof(System.Decimal));
table.Columns.Add("Difference", typeof(System.Int32));
table.Columns.Add("Date", typeof(System.DateTime));
table.Columns.Add("OnSale", typeof(System.Boolean));
for (int i = 0; i < 5; i++)
{
DataRow row = table.NewRow();
row["ID"] = ids[i];
row["Name"] = names[i];
row["Fee"] = fee[i];
row["Price"] = prices[i];
row["Discount"] = discounts[i];
row["Difference"] = differences[i];
row["Date"] = DateTime.Parse(dates[i]);
row["OnSale"] = onSale[i];
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
GridView1.UseAccessibleHeader = true;
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}

Before you build and test your web page, add the following CSS styles inside page head section to add some spice to your GridView.
<style type="text/css">
th
{
cursor:pointer;
background-color:#dadada;
color:Black;
font-weight:bold;
text-align:left;
}
th.headerSortUp
{
background-image: url(images/asc.gif);
background-position: right center;
background-repeat:no-repeat;
}
th.headerSortDown
{
background-image: url(images/desc.gif);
background-position: right center;
background-repeat:no-repeat;
}
td
{
border-bottom: solid 1px #dadada;
}
</style>

Add the following JQuery and Tablesorter javascript files references inside page head section.
<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
<script src="scripts/jquery.tablesorter.min.js" type="text/javascript"></script>
Click here for table sorter plugin
Finally call the tablesorter function on GridView to make your GridVeiw sortable.
<script type="text/javascript">
$(document).ready(function() {
$("#GridView1").tablesorter();
});
</script>

You can see how easy is to add client side sorting functionality to your GridView using the Tablesorter plugin. You just need to call a single function Tablesorter to implement basic sorting. However, there are many other options to customize the sorting functionality, and I will recommend you to visit the Tablesorter plugin home page to read the documentation for all the available options.

ASP.NET GridView Mouseover Hover Effect using JQuery

JQuery API has many CSS related functions, which can be used to create many UI effects in the modern web applications. The most common of those methods are addClass, removeClass and toggleClass, which add, remove or toggle CSS classes to any matched element. In this Tutorial, I will show you how you can create a simple mouseover hover effect on ASP.NET GridView Rows using JQuery CSS related methods.

To get things started, create an ASP.NET website and add a GridView control to the page from the Data Category in Toolbox. The following code shows the GridView control I am using for the demonstration of this tutorial. Please set the appropriate properties as shown in the code snippet below.

<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" BackColor="White" Font-Size="10"
Font-Names="Verdana" BorderColor="#000000" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" Width="400px" CellSpacing="0" GridLines="Horizontal">
</asp:GridView>

</form>

Next I am binding the GridView with a DataTable object that I created in the Page Load event in the code behind file. To keep things simple I am not connecting any database as it is not the purpose of this tutorial. I created a DataTable object with three columns and filled it with some rows using for loop. The complete code of the Page Load event is shown below:

protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Salary", typeof(decimal));
for (int i = 1; i < 8; i++)
{
DataRow row = table.NewRow();
row["ID"] = i;
row["Name"] = "Name " + i;
row["Salary"] = 10000 * i;
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
if (GridView1.Rows.Count > 0)
{
GridView1.UseAccessibleHeader = true;
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;

}
}

By default, The GridView control doesn’t render the <th> tags for the header row which can be an issue for sites where standard compliance and accessibility are important. When we set the property UseAccessibleHeader = true, it replaces the <td> elements of the header row with the correct <th> element. The HeaderRow.TableSection property of GridView control generates <thead> and <tbody> tags to make generated code more accessible. Build and run your project, and you will see the following output.

GridView without Highlighting

Although the above output looks very simple but the important thing to note is the HTML generated by the GridView control. Please check the source code of the page from the browser View Source option and see the HTML table code is generated. Next you need to add following CSS style rules inside the <head> section of the page. We will use the headerRow, highlightRow and selectedRow CSS classes in JQuery code in few minutes.

<style type="text/css">
th
{
text-align:left;
}
.headerRow
{
background-color: #000000;
color:White;
font-weight:bold;
}
.highlightRow
{
background-color: #dadada;
cursor: pointer;
border:solid 1px black;
}
.selectedRow
{
background-color: #808080;
cursor: pointer;
border:solid 1px black;
color:White;
}
</style>

Next add the JQuery script file reference inside the <head> section of the page depending on the script file location and JQuery version you are using.

<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>

Next add the following JQuery code inside a script block in<head>section of the page.

<script type="text/javascript">
$(document).ready(function () {
$('#GridView1 thead').addClass('headerRow');
$('#GridView1 tbody tr').mouseover(function () {
$(this).addClass('highlightRow');
}).mouseout(function () {
$(this).removeClass('highlightRow');
}).click(function () {
$(this).toggleClass('selectedRow');
});

});
</script>

The code defines typical JQuery ready method, which is used to access and manipulate DOM elements when they are loaded by the browser. The first line of code uses a JQuery selector to select<thead>section of the html table and adds a CSS class to the element using JQuery APIaddClass method.

$('#GridView1 thead').addClass('headerRow');

Next I am adding a sequence of three JQuery events mouseover, mouseout and click to the table rows<tr>elements.

$('#GridView1 tbody tr').mouseover(function () {
$(this).addClass('highlightRow');
}).mouseout(function () {
$(this).removeClass('highlightRow');
}).click(function () {
$(this).toggleClass('selectedRow');
});

Each one of these events takes a function handler as a parameter in which you can write code you want to execute when these events occur on table rows. I am using addClass method to add CSS class inside mouseover event handler and removing the same CSS class using theremoveClass method inside mouseout event handler. This will give you hover effect when you will move the mouse on table rows. The clickevent handler uses JQuery API toggleClass method which adds or removes CSS classes based on the class presence. You can read more about these methods at the following URL on JQuery website.
http://api.jquery.com/category/css
If you have followed the complete tutorial with me you will see the GridView with mouseover hover and click effects as shown in the following figure.

GridView with mouseover hover and click effect

I hope you have enjoyed this tutorial as much as I have enjoyed writing it. You can download the full source code of this tutorial by clicking theDownload Source Code button at the top of this page. You can also watch the live demo by clicking the Live Demo button.

Download Source Code

Select Deselect GridView Rows using a Checkbox in JQuery

Many websites require functionality for letting their site visitors to select and deselect all the rows in GridView using a single checkbox normally available in the header row. You may have seen the examples of such functionality in Yahoo Mail or Hotmail inbox where you can select all the emails by clicking the single Checkbox on top of the email's grid. In this tutorial, I will show you how you can provide this functionality in ASP.NET GridView control using few lines of JQuery code.

Select Unselect GridView Rows

To get started, create an ASP.NET website and drag a GridView control on the page. For this tutorial, I am using ID, Name and Salary columns, so I added three bound fields and one TemplateField that will contain the checkboxes in the header as well as in the individual row. Following is the complete HTML source for the GridView control.

<asp:GridView ID="GridView1" runat="server" Font-Size="10pt"
Font-Names="Verdana" CellPadding="4" Width="400px" GridLines="None"
ForeColor="#333333" AutoGenerateColumns="false">
<RowStyle BackColor="#EFF3FB" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkHeader" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Salary" HeaderText="Salary" />
</Columns>
</asp:GridView>

To keep this tutorial simple, I am not connecting my GridView with the database and showing some sample data in the GridView. Add the following code in the Page Load event of the page to add few rows of data.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Salary", typeof(decimal));
for (int i = 1; i < 8; i++)
{
DataRow row = table.NewRow();
row["ID"] = i;
row["Name"] = "Name " + i;
row["Salary"] = 10000 * i;
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
}


Now we need only few lines of JQuery code to provide the functionality of selecting or deselecting rows using the checkbox added in the header of the GridView. Add the JQuery script file reference in the head element of the page.

<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
Add the following JavaScript block inside the head element of the page.
<script type="text/javascript">
$(document).ready(function() {
var headerCheckbox = $('#GridView1 > tbody > tr > th > input:checkbox');
headerCheckbox.click(function() {
var headerChecked = $(this).attr('checked');
var rowCheckboxes = $('#GridView1 > tbody > tr > td > input:checkbox');
rowCheckboxes.attr('checked', headerChecked);
});

});
</script>


The above code is using typical JQuery ready function to add some JQuery statements or code. The first line access the checkbox available in the header row of the GridView using JQuery selector.
var headerCheckbox = $('#GridView1 > tbody > tr > th > input:checkbox');
Once we have the reference of header checkbox, we are using the click event function handler that will allow us to run some code every time user will click the header checkbox. Inside click event function handler, the first line stores the current state of the header checkbox in aheaderChecked variable. The second line gets the reference of all the checkboxes in all the rows in GridView and then set their state to the same state as the header checkbox using JQuery attr function.

headerCheckbox.click(function() {
var headerChecked = $(this).attr('checked');
var rowCheckboxes = $('#GridView1 > tbody > tr > td > input:checkbox');
rowCheckboxes.attr('checked', headerChecked);
});


Build and test your web page and click the checkbox in the header row, and you will be able to select or deselect all checkboxes in GridView rows. You can click the Live Demo button to see the working example of this tutorial.

Download Source Code Download Source Code Live Demo Live Demo

Export ASP.NET GridView to Excel

Many developers use GridView control to display web reports in their ASP.NET websites. GridView control render data in a tabular form just like HTML tables but it lack the functionality of exporting its contents to any other format such as Excel of PDF file. It is very common requirements of many clients to export web report data to Excel file so that they can perform some analysis using Excel built in features. In this Tutorial I will show you how to export GridView control as Excel File.

For the purpose of this tutorial, I setup a sample ASP.NET page showing products from Northwind database using GridView control. I hope the data binding code will not be new for you if you have already read some of the articles related to GridView control on my website. Following is the preview of the page I am going to use to export to excel.

Export to Excel Page

Following Code shows how you can bind data to GridView control in the Page_Load event. Please keep in mind that for brevity I am storing connection string in the code. You should always store your database connection strings in web.config.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
string constr = @"Server=SampleServer;Database=NORTHWND;uid=test; Password=test;";
string query = "SELECT ProductID, ProductName, UnitPrice FROM Products";
SqlDataAdapter da = new SqlDataAdapter(query, constr);
DataTable table = new DataTable();
da.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}


As you can guess from the above screen shot that the button “Export to Excel” will implement the main export functionality. The code below is the button click event handler code to export GridView control contents to excel but you can use similar code to export to other formats by changing the ContentType property.

Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Products.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
GridView1.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();


Sometimes, when you render any asp.net control dynamically as I am doing with the GridView control in this tutorial, you can get HttpExceptionwith the following message:
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
The problem can be solved by overriding Page class VerifyRenderingInServerForm method which confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.

public override void VerifyRenderingInServerForm(Control control)
{ }


When you will click the Export to Excel button you will see the following dialog box asking you to open or save dynamically generated Excel file.

Open/Save Excel File Dialog Box

Following screen shot shows you how the data is saved in Excel file.

export_to_excel_preview.JPG

Display GridView Row Details using ASP.NET AJAX Popup Control

When you display records using ASP.NET GridView control it displays all the columns on the page and often you want to display only few columns in GridView due to the available space on the page. You can easily achieve this functionality by adding your own columns declaratively in the GridView control. But if you want to display other columns in a popup window for each row in the GridView control you need to use AJAX Popup Control with the GridView. In this tutorial I will show you how you can display GridView row details using ASP.NET AJAX Popup control extender.

ASP.NET AJAX Popup Control Extender

To start this tutorial, create a new website in Visual Studio 2008 and add ScriptManager control on the page. This control is required to use any AJAX functionality on ASP.NET page.

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

Next you need to add GridView control on the page that has AutoGenerateColumns property set to false to stop ASP.NET to generate columns automatically. You also need to attach OnRowCreated event handler with the grid which I will use later in this tutorial to attach some JavaScript events with a magnify icon to display popup window on mouse over. Following is the complete markup of the GridView control.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" Font-Names="Verdana" Font-Size="10pt"
onrowcreated="GridView1_RowCreated">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="Product ID" />
<asp:BoundField DataField="ProductName" HeaderText="Product Name" />
<asp:TemplateField ItemStyle-Width="40" ItemStyle-HorizontalAlign="Right">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/magnify.gif" />
<ajax:PopupControlExtender ID="PopupControlExtender1" runat="server"
PopupControlID="Panel1"
TargetControlID="Image1"
DynamicContextKey='<%# Eval("ProductID") %>'
DynamicControlID="Panel1"
DynamicServiceMethod="GetDynamicContent" Position="Bottom">
</ajax:PopupControlExtender>
</ItemTemplate>
</asp:TemplateField>

</Columns>
<HeaderStyle BackColor="#336699" ForeColor="White" />
</asp:GridView>


The most important thing in the above markup is the TemplateField column definition in which I have used an image control to display magnify icon and ASP.NET AJAX Popup Control Extender.
The PopupControlID property needs the id of the control you want to use as a popup window with AJAX Popup Control in this case I have used Panel control.
The TargetControlID property needs the id of the control that will display the popup window in this case I have used Image1 control that shows magnify icon in the GridView column.
The DynamicServiceMethod property needs the name of the web service method you want to call for every popup window to load additional details from the database.
The DynamicContextKey property needs the dynamic value you want to pass to the dynamic web service method. In this example I am passing ProductID to load more details of the product in the popup window dynamically.
In the end you need a Panel control on the page which will be used as a popup window by the PopupControlExtender control.
<asp:Panel ID="Panel1" runat="server"> </asp:Panel>
Now I am moving to the code behind file of the ASP.NET page that has Page Load event to bind data with the GridView control as shown below:

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
string constr = "Server=TestServer;Database=SampleDatabase;uid=test;pwd=test;";
string query = "SELECT ProductID, ProductName FROM Products";
SqlDataAdapter da = new SqlDataAdapter(query, constr);
DataTable table = new DataTable();
da.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}

Next you need the OnRowCreated event definition that will perform two operations during the creation of every data row of the GridView control. First it will find the Popup Extender Control using the FindControl method and will add a unique behavior id with each popup control. Secondly it will find Image control in every row and will attach showPopup() and hidePopup() script with the image onmouseover and onmouseout events. This is required to display popup window on mouse over and hide popup window on mouse out automatically.

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
PopupControlExtender pce = e.Row.FindControl("PopupControlExtender1") as PopupControlExtender;
string behaviorID = "pce_" + e.Row.RowIndex;
pce.BehaviorID = behaviorID;
Image img = (Image)e.Row.FindControl("Image1");
string OnMouseOverScript = string.Format("$find('{0}').showPopup();", behaviorID);
string OnMouseOutScript = string.Format("$find('{0}').hidePopup();", behaviorID);
img.Attributes.Add("onmouseover", OnMouseOverScript);
img.Attributes.Add("onmouseout", OnMouseOutScript);
}
}


In the end, you need the definition of GetDynamicContent service method that will be called by every ASP.NET AJAX Popup Control Extender to load dynamic data from the database and to display additional details in the popup window. The first few lines in the method below are loading additional columns from the Products table in database. The StringBuilder object is created to build html string for the tabular output in the popup window. You can build any type of html for display such as bullets, paragraphs, links etc.

[System.Web.Services.WebMethodAttribute(),
System.Web.Script.Services.ScriptMethodAttribute()]
public static string GetDynamicContent(string contextKey)
{
string constr = "Server=TestServer;Database=SampleDatabase;uid=test;pwd=test;";
string query = "SELECT UnitPrice, UnitsInStock, Description FROM Products WHERE ProductID = " + contextKey;
SqlDataAdapter da = new SqlDataAdapter(query, constr);
DataTable table = new DataTable();
da.Fill(table);
StringBuilder b = new StringBuilder();
b.Append("<table style='background-color:#f3f3f3; border: #336699 3px solid; ");
b.Append("width:350px; font-size:10pt; font-family:Verdana;' cellspacing='0' cellpadding='3'>");
b.Append("<tr><td colspan='3' style='background-color:#336699; color:white;'>");
b.Append("<b>Product Details</b>"); b.Append("</td></tr>");
b.Append("<tr><td style='width:80px;'><b>Unit Price</b></td>");
b.Append("<td style='width:80px;'><b>Stock</b></td>");
b.Append("<td><b>Description</b></td></tr>");
b.Append("<tr>");
b.Append("<td>$" + table.Rows[0]["UnitPrice"].ToString() + "</td>");
b.Append("<td>" + table.Rows[0]["UnitsInStock"].ToString() + "</td>");
b.Append("<td>" + table.Rows[0]["Description"].ToString() + "</td>");
b.Append("</tr>");
b.Append("</table>");
return b.ToString();
}


If you have implemented everything in this tutorial properly you will see the output similar to the figure shown in the start of this tutorial. Please make sure that you have imported the following namespaces in the code file before you run this project.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using AjaxControlToolkit;
using System.Text;

Also make sure that you have registered the AjaxControlToolkit in your aspx file using the Register directive as shown below:

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>

Source:ezzylearning

Using ASP.NET AJAX HoverMenu Control with GridView

Source:ezzylearning

ASP.NET AJAX Controls Toolkit provides many useful controls to ASP.NET developers to build modern rich internet applications. One such control is HoverMenu control that enables you to attach popup menu with any ASP.NET control. It can be used as a simple tooltip which can be attached with a TextBox and showing users what they are suppose to enter in the textbox or like many modern ecommerce shopping applications, it can be used to display larger image of the product when user move mouse on the product thumbnail image. In this tutorial, I will show you how to achieve this functionality using HoverMenu and GridView controls.

ASP.NET AJAX HoverMenu Control

To start this tutorial, I have created a new page which has a ScriptManager control on the top. This control is required every time you want to use any ASP.NET AJAX feature or control on you website.

<asp: ScriptManager ID="ScriptManager1" runat="server"></asp: ScriptManager>
Next, I am adding a GridView control on the page that has AutoGenerateColumns property set to false and adding three BoundField columns and a TemplateField column as shown in the markup below:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None" BorderColor="#628BD7"
BorderStyle="Solid" BorderWidth="2px">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="Product ID" />
<asp:BoundField DataField="ProductName" HeaderText="Product Name" />
<asp:BoundField DataField="UnitPrice" HeaderText="Unit Price" />
<asp:TemplateField HeaderText="Picture">
<ItemTemplate>
<asp:Image runat="server" ID="thumbnailImage"
ImageUrl='<%# Eval("Picture") %>' Width="70" Height="60" />
<ajax:HoverMenuExtender ID="HoverMenuExtender1" runat="server"
PopupControlID="popupImage"
TargetControlID="thumbnailImage"
OffsetX="10" OffsetY="5"
PopupPosition="Right"
PopDelay="100" HoverDelay="100">
</ajax:HoverMenuExtender>

<asp:Panel runat="server" ID="popupImage" BorderColor="#628BD7"
BorderStyle="Solid" BorderWidth="7px">
<asp:Image runat="server" ID="mainImage"
ImageUrl='<%# Eval("Picture") %>' />
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
</asp:GridView>

In the markup above, the ItemTemplate of the TemplateField column is first defining the small thumbnail image of the product. This image will be shown to the user when the GridView will be displayed on the page.

<asp:Image runat="server" ID="thumbnailImage"
ImageUrl='<%# Eval("Picture") %>' Width="70" Height="60" />
Next I added HoverMenu control in the ItemTemplate and setting the basic properties of the control.<ajax:HoverMenuExtender ID="HoverMenuExtender1" runat="server"
PopupControlID="popupImage"
TargetControlID="thumbnailImage"
OffsetX="10" OffsetY="5"
PopupPosition="Right"
PopDelay="100" HoverDelay="100">
</ajax:HoverMenuExtender>

Finally I added a Panel control that will be used as a popup window by the HoverMenu control.  This Panel can display any type of contents but for the purpose of this tutorial I am only showing the Product Image using an Image control.

<asp:Panel runat="server" ID="popupImage" BorderColor="#628BD7"
BorderStyle="Solid" BorderWidth="7px">
<asp:Image runat="server" ID="mainImage"
ImageUrl='<%# Eval("Picture") %>' />
</asp:Panel>

The following is the explanation of HoverMenu control properties.
TargetControlID:  This property needs the reference of the target control. HoverMenu display itself automatically when you move mouse on the target control. In this case I have given the id of the small Image control which is defined just above the HoverMenu control.
PopupControlID:  This property needs the id of the control you want to use as a popup window with AJAX HoverMenu Control in this case I have used Panel control which is defined just after the HoverMenu control.
PopupPosition: This is optional property and can be set to Left, Right, Top, Bottom or Center. It specifies the relative position of the HoverMenu control with respect to target control. OffsetX and OffsetY: These two properties specify the number of pixels to offset the HoverMenu control horizontally or vertically from its default position as specified by PopupPosition property.
PopDelay: This property specified the number of milliseconds you want the HoverMenu popup control to remain visible after the user has moved mouse out of the control.
HoverDelay: This property specified the number of milliseconds you want to elapse before the HoverMenu popup control to appears to the user.
HoverCssClass: The name of the CSS class to apply to the target control when the hover menu popup is visible. For brevity, I have not used this property in this tutorial as I directly apply border color and style to the target Panel control.
Animations:  HoverMenu control also supports animations property which you can use to apply generic animation effects to your HoverMenu control.
To complete this tutorial, don’t forget to bind your GridView control with the Products Table in database. The products table I am using for this tutorial has four columns ProductID, ProductName, UnitPrice and Picture. The Picture column is storing the actual image url as string value such as “images/canon_digital_camera.jpg”. Following is the code I am using to bind the GridView with products Table.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
string constr = "Server=TestServer; Database=SampleDB; uid=sa; pwd=123;";
string query = "SELECT ProductID, ProductName, UnitPrice, Picture FROM Products";
SqlDataAdapter da = new SqlDataAdapter(query, constr);
DataTable table = new DataTable();
da.Fill(table); GridView1.DataSource = table;
GridView1.DataBind();
}

GridView Manual Implementation


Open VisualStudio => Select new Website=> give name to the website as GridView_Demo
Add a asp.net webpage to website Default.aspx
Add a Gridview to the page and put AutoGenerateColumns="False"
    <asp:GridView ID="GridView2" runat="server" BackColor="White"
        BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4"
        Width="691px" AutoGenerateColumns="False">
        <Columns>       
            <asp:BoundField HeaderText="Party Name" DataField="patName" />
            <asp:BoundField HeaderText="Party Id" DataField="patId" />
            <asp:BoundField HeaderText="Email" DataField="email" />
        </Columns>
        <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
        <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
        <RowStyle BackColor="White" ForeColor="#330099" />
        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
        <SortedAscendingCellStyle BackColor="#FEFCEB" />
        <SortedAscendingHeaderStyle BackColor="#AF0101" />
        <SortedDescendingCellStyle BackColor="#F6F0C0" />
        <SortedDescendingHeaderStyle BackColor="#7E0000" />
    </asp:GridView>

In code behind file put the fallowing code in page_load
            DataTable dt = new DataTable();
            DataColumn patName = new DataColumn("patName");
            DataColumn patId = new DataColumn("patId");
            DataColumn email = new DataColumn("email");
           
            dt.Columns.Add(patName);
            dt.Columns.Add(patId);
            dt.Columns.Add(email);
           
            DataRow row = null;
            foreach (string record in records)
            {
                string[] cols = record.Replace("||", "|").Split('|');
                if (cols.Length > 1)
                {
                    row = dt.NewRow();
                    row[patId] = cols[1].Trim();
                    row[patName] = cols[0].Trim();
                    row[email] = cols[2].Trim();
                    dt.Rows.Add(row);
                }
}
            GridView2.DataSource = dt;
            GridView2.DataBind();
The gridview in webpage will look like fallowing image:
Capture