• Sorting Tabular Data in ASP.NET

    by Venkata Koppaka | Jun 05, 2010

    In this post I will talk about how to build tabular data using ADO.NET EntityFramework and sort tabular / grid data using JQuery table sorter plugin. For the sake of demo I will use ASP.NET 4 and .NET Framework 4.

    Fire up Visual Studio 2010 and Create a New ASP.NET WebSite. For this demo I will use ADO.NET Entity Framework to get a list of Products from the database.

    I will use AdventureWorks Database for the sake of this demo.

    Add a new ADO.NET Entity Data Model, select “generate from database”, hit next choose the and add the product’s table

     

    Add a new C# Class and class it Product.cs this class will be in the same namespace as the EntityDataModel and the Product class will extend as a partial class from the class created by ADO.NET EntityFramework. Here is how the class should look like –

    1 using System; 
    2 using System.Collections.Generic; 
    3 using System.Linq; 
    4 using System.Web; 
    5  
    6 /// <summary> 
    7 /// Summary description for Product 
    8 /// </summary> 
    9 ///  
    10 namespace AdventureWorksModel 
    11
    12     public partial class Product 
    13     { 
    14         public IQueryable<Product> GetProducts() 
    15         { 
    16             AdventureWorksEntities db = new AdventureWorksEntities(); 
    17             return db.Products.Take(200); 
    18         } 
    19     } 
    20

    We created a method called GetProducts which just takes the top 200 rows in from the Products table. This method will return a List of Products of type IQueryable.

    Now add a new ASP.NET WebForm and call it Products.aspx. In Products.aspx drag drop a GridView and set its DataSource as ObjectDataSource, in the GridView tasks choose new DataSource and Choose object as Data Source Type,

     

    From the choose a Business Object Screen Choose the Products Class we just created.

     

    For the select method Choose the GetProducts method we created earlier.

     

     

    Choose the necessary columns from the gridview, I choose a few columns for this demo. Once you are done with choosing columns your Products.aspx code should look something like this –

      

    1     <asp:GridView ID="gdvProducts" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1"> 
    2         <Columns> 
    3             <asp:BoundField DataField="ProductID" HeaderText="ProductID" SortExpression="ProductID" /> 
    4             <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> 
    5             <asp:BoundField DataField="ProductNumber" HeaderText="ProductNumber" SortExpression="ProductNumber" /> 
    6             <asp:CheckBoxField DataField="MakeFlag" HeaderText="MakeFlag" SortExpression="MakeFlag" /> 
    7             <asp:CheckBoxField DataField="FinishedGoodsFlag" HeaderText="FinishedGoodsFlag" SortExpression="FinishedGoodsFlag" /> 
    8             <asp:BoundField DataField="Color" HeaderText="Color" SortExpression="Color" /> 
    9             <asp:BoundField DataField="SafetyStockLevel" HeaderText="SafetyStockLevel" SortExpression="SafetyStockLevel" /> 
    10             <asp:BoundField DataField="ReorderPoint" HeaderText="ReorderPoint" SortExpression="ReorderPoint" /> 
    11             <asp:BoundField DataField="StandardCost" HeaderText="StandardCost" SortExpression="StandardCost" /> 
    12             <asp:BoundField DataField="ListPrice" HeaderText="ListPrice" SortExpression="ListPrice" /> 
    13         </Columns> 
    14     </asp:GridView> 
    15     <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetProducts" 
    16         TypeName="AdventureWorksModel.Product"></asp:ObjectDataSource> 

    Run the application and this is how your products list will show up.

     

    Download JQuery 1.4.1 and tablesorter plugins and them to the scripts folder of the website. Once done add these scripts to the head section of master page.

    1     <link href="~/Content/tablsorter.css" rel="stylesheet" type="text/css" /> 
    2     <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> 
    3     <script src="Scripts/jquery.tablesorter.js" type="text/javascript"></script> 

    In the HTML for gridview now let’s add a CSS class so that we can use it find the table by JQuery.

    1 <asp:GridView ID="gdvProducts" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1" CssClass="tablesorter"> 
     

    Note the CssClass Property above which is set to tablesorter.

    Now add the following script in the products.aspx page –

    1         <script type="text/javascript"> 
    2             $(document).ready(function () { 
    3  
    4                 $('.tablesorter').tablesorter(); 
    5  
    6             }); 
    7         </script> 

    Run the application. Your application should be something similar to this –

     

    Notice the sort up and sort down arrows.

    Hope this helps.

    Cheers,

    Venkata

    Go comment!
  • Test Technorati Claim

    by Venkata Koppaka | May 04, 2010
    Test
    Go comment!
  • Creating a Printer Friendly ASP.NET Page

    by Venkata Koppaka | Apr 19, 2010

    This post is a quick snippet of code to create a Printer Friendly version of any ASP.NET page.

    Create a DIV which holds the content of your ASP.NET Page , so enclose the entire content that you want to print inside a div -

     

    1 <div id="ContentDiv"> 
    2       PUT ALL OF YOUR CONTENT HERE 
    3 </div> 

    Then create a Hyperlink for the user to click, to get to the print friendly page

    1 <a href="#" onclick="JavaScript:PrintPage('ContentDiv')">Printer Friendly Page</a> 

     

    Include this JavaScript Function in your page for printing the webpage

    1 <script type="text/javascript"> 
    2     function PrintPage(divID) { 
    3         var windowOptions = "toolbar=no,location=no,directories=yes,menubar=no,"; 
    4         windowOptions += "scrollbars=yes,width=750,height=600,left=100,top=25"; 
    5         var printContent = document.getElementById(divID); 
    6         var printWindow = window.open("", "", windowOptions); 
    7         printWindow.document.write(printContent.innerHTML); 
    8         printWindow.document.close(); 
    9         printWindow.focus(); 
    10         printWindow.print(); 
    11     } 
    12 </script> 

     

    The printContent.innerHTML will give you all the required data on the page that has to be printed.

    Hope this hepls,

    Cheers,

    Venkata


    Go comment!
  • Sorting Tabular Data in ASP.NET MVC

    by Venkata Koppaka | Apr 17, 2010

    In this post I will talk about how to use TableSorter Plugin (http://tablesorter.com/docs/) in a ASP.NET MVC application.

    I will be using .NET 4 and ASP.NET MVC2 for the demo code in this post.

    I will be using AdventureWorks database that can be downloaded from codeplex as a sample database for SQL Server 2008.

     Add a ADO.NET Entity Data Model, for this demo purpose I have added Product table to the data designer.

    Add a Controller to the MVC Application, call it ProductsController.

    Create a Index Action Method in the controller and use the following code to get the data.

    1 namespace TableSorter_MVC.Controllers 
    2
    3     public class ProductsController : Controller 
    4     { 
    5          
    6         AdventureWorksEntities db = new AdventureWorksEntities(); 
    7  
    8         public ActionResult Index() 
    9         { 
    10             IList<Product> products = db.Products.Take(200).ToList(); 
    11  
    12             return View(products); 
    13         } 
    14  
    15     } 
    16

    Add a View to show a List of products and strongly type it to Product Table.

    Here is how a view code for the list would look like -

    1 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<TableSorter_MVC.Models.Product>>" %> 
    2  
    3 <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> 
    4     Index 
    5 </asp:Content> 
    6 <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
    7     <h2> 
    8         Index</h2> 
    9     <table class="tablesorter"> 
    10         <thead> 
    11             <tr> 
    12                 <th> 
    13                     ProductID 
    14                 </th> 
    15                 <th> 
    16                     Name 
    17                 </th> 
    18                 <th> 
    19                     ProductNumber 
    20                 </th> 
    21                 <th> 
    22                     MakeFlag 
    23                 </th> 
    24                 <th> 
    25                     FinishedGoodsFlag 
    26                 </th> 
    27                 <th> 
    28                     Color 
    29                 </th> 
    30                 <th> 
    31                     SafetyStockLevel 
    32                 </th> 
    33                 <th> 
    34                     ReorderPoint 
    35                 </th> 
    36                 <th> 
    37                     StandardCost 
    38                 </th> 
    39                 <th> 
    40                     ListPrice 
    41                 </th> 
    42             </tr> 
    43         </thead> 
    44         <tbody> 
    45             <% foreach (var item in Model) 
    46                { %> 
    47             <tr> 
    48                 <td> 
    49                     <%: item.ProductID %> 
    50                 </td> 
    51                 <td> 
    52                     <%: item.Name %> 
    53                 </td> 
    54                 <td> 
    55                     <%: item.ProductNumber %> 
    56                 </td> 
    57                 <td> 
    58                     <%: item.MakeFlag %> 
    59                 </td> 
    60                 <td> 
    61                     <%: item.FinishedGoodsFlag %> 
    62                 </td> 
    63                 <td> 
    64                     <%: item.Color %> 
    65                 </td> 
    66                 <td> 
    67                     <%: item.SafetyStockLevel %> 
    68                 </td> 
    69                 <td> 
    70                     <%: item.ReorderPoint %> 
    71                 </td> 
    72                 <td> 
    73                     <%: String.Format("{0:F}", item.StandardCost) %> 
    74                 </td> 
    75                 <td> 
    76                     <%: String.Format("{0:F}", item.ListPrice) %> 
    77                 </td> 
    78             </tr> 
    79             <% } %> 
    80         </tbody> 
    81     </table> 
    82 </asp:Content> 
    83  

    Please Note : For the table sorter plugin to work the table should have a <thead> and <tbody> for heading and body respectively.

    Download the tablesorter.zip file from table sorter website. Add jquery.tablesorter.js file that comes in tablesorter.zip . For this example I picked the blue theme that comes in with tablesorter.

    Add the site.css file that is in the blue theme of tablesorter to the content folder of the MVC application. Add the 3 images(asc.gif,desc.gif,bg.gif) to the content folder of the application as well.

    Add these lines to include scripts and styles in the ASP.NET MVC master page.

    1 <head runat="server"> 
    2     <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title> 
    3     <link href="../../Content/Site.css" rel="stylesheet" type="text/css" /> 
    4     <link href="../../Content/tablsorter.css" rel="stylesheet" type="text/css" /> 
    5     <script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script> 
    6     <script src="../../Scripts/jquery.tablesorter.js" type="text/javascript"></script> 
    7 </head> 

    Once these are done, you just need to add a single line of script in Index.aspx view to make the table sortable.

    1     <script type="text/javascript"> 
    2         $(document).ready(function () { 
    3  
    4             $('.tablesorter').tablesorter(); 
    5  
    6         }); 
    7     </script> 

    Here is how the page is going to look like

    By default -

    After Sorting -

    And 

    Hope this helps

    I will be writing another post on how to use tablesorter in  ASP.NET application shortly.

    Cheers,

    Venkata

    Go comment!
  • Round to Nearest 10,100, or 10 POW N

    by Venkata Koppaka | Apr 02, 2010

    This one is a quick code snippet,

    Here is a method which can round a value to nearest 100,1000, or any 10 Pow N.

    This method follows the rounding rules –

    1private static int RoundToNDigits(double value,int digits)  
    2        {  
    3            int valueAfterDecimal = Convert.ToInt32(value % Math.Pow(10, digits));  
    4            int valueBeforeDecimal = Convert.ToInt32(value) / Convert.ToInt32(Math.Pow(10, digits));  
    5            if (valueAfterDecimal < 50)  
    6            {  
    7                return valueBeforeDecimal * Convert.ToInt32(Math.Pow(10, digits));  
    8            }  
    9            else if (valueAfterDecimal > 50)  
    10            {  
    11 
    12                return Convert.ToInt32((valueBeforeDecimal + 1) * Math.Pow(10, digits));  
    13            }  
    14            else  
    15            {  
    16                if (valueBeforeDecimal % 2 == 0)  
    17                    return (valueBeforeDecimal + 1) * Convert.ToInt32(Math.Pow(10, digits));  
    18                else  
    19                    return valueBeforeDecimal * Convert.ToInt32(Math.Pow(10, digits));  
    20            }  
    21        } 

    Hope this helps,
    Cheers,
    Venkata
    Go comment!