C1GridView lets you display items from a data source in an interactive, fully customizable table. And a common scenario is to display a ContextMenu and provide some functionality such as exporting to various formats etc.

In this blog, I will demonstrate how you can display a ContextMenu for C1Gridview and provide the export functionality to the users. Here is how it would look:

Demo1

First of all, you need to create an HTML table which will be displayed as a context menu for C1GridView. Each tag will correspond to an item in the ContextMenu. Here is the sample code :


<table style="width: 100%;">
<tbody>
<tr>
<td onclick="fnExcel()">Export to Excel</td>
</tr>
<tr>
<td onclick="fnCSV()">Export to Text File</td>
</tr>
<tr>
<td onclick="fnPDF()">Export to PDF</td>
</tr>
</tbody>
</table>


The basic functionality of a ContextMenu is to display when the end user right clicks on the container element. And hence, we will use the contextmenu event of C1GridView row object and position the ContextMenu using CSS like below:


$(document).ready(function ()
{
$("#myMenu").hide();
$("table[id$='C1GridView1'] &gt; tbody &gt; tr").bind('contextmenu', function (e)
{
$("#myMenu").hide();
e.preventDefault();
rowid = $(this).children(':first-child').text();
if (!isNaN(rowid))
{
//call context menu here
$("#myMenu").css({
top: e.pageY + "px",
left: e.pageX + "px",
position: 'absolute'
});
$("#myMenu").show();
}
});
});


Now, we have displayed the ContextMenu but we need to hide it when the user clicks anywhere else on the web page. To accomplish this you can use the 'hide' method in the click event of the document.


//Code to hide context menu when user clicks anywhere on the grid
$(document).bind('click', function (e)
{
$("#myMenu").hide();
});


If you re-look at the HTML code above, we have binded the click event of the tags/ menu items to specific methods. These methods define the action performed when the menu item is clicked. In this blog, we are implementing export functionality of C1GridView but you may customize these methods as per your requirements. Here is the code from one of the methods:


//Handle the click events of the menu items.
function fnExcel()
{
var fileName = "Export";
var type = "xlsx";
var excelSetting = {
showGridLines: true,
autoRowHeight: true
};
var url = "http://demos.componentone.com/ASPNET/ExportService/exportapi/grid";
$("#C1GridView1").c1gridview("exportGrid", fileName, type, excelSetting, url);
}


In this blog we used the context menu to provide the export functionality. You may enhance this menu to provide other options. It would be interesting if you would share what other options you added to this context menu.

Download C# Code
Download VB Code