<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>.toString() &#187; grid</title>
	<atom:link href="http://www.dottostring.com/tag/grid/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dottostring.com</link>
	<description>Programming is our passion</description>
	<lastBuildDate>Sun, 04 Oct 2009 15:57:48 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Adding support for .NET datatypes to ExtJs Grid (DateTime, Boolean and Currency)</title>
		<link>http://www.dottostring.com/2009/04/adding-support-for-net-datatypes-to-extjs-grid-datetime-boolean-and-currency/</link>
		<comments>http://www.dottostring.com/2009/04/adding-support-for-net-datatypes-to-extjs-grid-datetime-boolean-and-currency/#comments</comments>
		<pubDate>Tue, 07 Apr 2009 21:10:56 +0000</pubDate>
		<dc:creator>Irfan</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[ExtJs]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[grid]]></category>
		<category><![CDATA[renderer]]></category>

		<guid isPermaLink="false">http://www.dottostring.com/?p=356</guid>
		<description><![CDATA[In our previous examples we had been using plain Strings in ExtJs grid.
Have a quick look at them:

On-Demand Paging using ExtJS Grid with Client-Centric ASP.NET AJAX (WebMethods)
Adding server side sorting to ExtJS Grid using WebMethods in ASP.NET

Today, we are going to deal with other Data types like DateTime, Boolean, Currency et cetera. For this purpose, [...]]]></description>
			<content:encoded><![CDATA[<p>In our previous examples we had been using plain Strings in ExtJs grid.<br />
Have a quick look at them:</p>
<ul>
<li><a href="/2008/12/on-demand-paging-using-extjs-grid-with-client-centric-asp-dot-net-ajax-webmethods/" target="_blank">On-Demand Paging using ExtJS Grid with Client-Centric ASP.NET AJAX (WebMethods)</a></li>
<li><a href="/2009/03/adding-server-side-sorting-to-extjs-grid-using-webmethods-in-aspnet/" target="_blank">Adding server side sorting to ExtJS Grid using WebMethods in ASP.NET</a></li>
</ul>
<p>Today, we are going to deal with other Data types like DateTime, Boolean, Currency et cetera. For this purpose, ExtJs ColumnModel provides and excellent config option <code><a href="http://extjs.com/deploy/ext/docs/output/Ext.grid.ColumnModel.html#config-renderer" target="_blank">renderer</a></code></p>
<p>Lets start with builtin format options of ExtJs. </p>
<pre name="code" class="js">
// create the grid
        var grid = new Ext.grid.EditorGridPanel({
            el:'grid-employees',
            width:650,
            height:300,
            title:'Sample Employees',
            store: store,
            stripeRows: true,
            loadMask: true,
            enableHdMenu: false,

            // grid columns
            columns:[{
                id: 'EmployeeID',
                dataIndex: 'EmployeeID',
                hidden:true
            },{
                header: "Login ID",
                dataIndex: 'LoginID',
                width: 150,
                sortable:true

            },{
                header: "Title",
                dataIndex: 'Title',
                width: 200,
                sortable:true
            },{
                header: "Birth Date",
                dataIndex: 'BirthDate',
                width: 100,
                sortable:true
            },{
                header: "Gender",
                dataIndex: 'Gender',
                width: 70,
                sortable:true
            },{
                header: "Salary",
                dataIndex: 'Salary',
                width: 70,
                renderer: 'usMoney',
                sortable:true
            },{
                header: "Salaried",
                dataIndex: 'SalariedFlag',
                width: 50,
                sortable:true
            }],
            // put paging bar on the bottom
            bbar: pagingBar
        });
</pre>
<p>Notice that for the dataIndex Salary, we have renderer option equal to <code><a href="http://extjs.com/deploy/ext/docs/output/Ext.util.Format.html#usMoney" target="_blank">usMony</a></code>. This will render all values in this column as usMoney. </p>
<p>Now lets play with some custom renderers. I have written two custom rederers. One is for DateTime object of .NET and the other is for Boolean object.</p>
<pre name="code" class="js">
        // Our own date renderer function
        function formatDate(value){
            return value ? value.dateFormat('F d, Y') : '';
        };

        // Our own boolean renderer
        function formatTrueFalse(value) {
            return value ? '&amp;#10003;': '&amp;#9747;';
        }
</pre>
<p>These functions are quite simple. They just return the formatted strings to be used in ColumnModel. Now we will use these renderers in our ColumnModel.</p>
<pre name="code" class="js">
        // create the grid
        var grid = new Ext.grid.EditorGridPanel({
            el:'grid-employees',
            width:650,
            height:300,
            title:'Sample Employees',
            store: store,
            stripeRows: true,
            loadMask: true,
            enableHdMenu: false,

            // grid columns
            columns:[{
        	    id: 'EmployeeID',
                dataIndex: 'EmployeeID',
                hidden:true
            },{
                header: "Login ID",
                dataIndex: 'LoginID',
                width: 150,
                sortable:true

            },{
                header: "Title",
                dataIndex: 'Title',
                width: 200,
                sortable:true
            },{
                header: "Birth Date",
                dataIndex: 'BirthDate',
                width: 100,
                renderer: formatDate,
                sortable:true
            },{
                header: "Gender",
                dataIndex: 'Gender',
                width: 70,
                sortable:true
            },{
                header: "Salary",
                dataIndex: 'Salary',
                width: 70,
                renderer: 'usMoney',
                sortable:true
            },{
                header: "Salaried",
                dataIndex: 'SalariedFlag',
                width: 50,
                renderer: formatTrueFalse,
                sortable:true
            }],
            // put paging bar on the bottom
            bbar: pagingBar
        });
</pre>
<p>And that&#8217;s all <img src='http://www.dottostring.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Now you will have a beautifully rendered grid. </p>
<p><img src="http://www.dottostring.com/wp-content/uploads/2009/04/custom-renderer-extjs-grid.png" alt="custom-renderer-extjs-grid" title="custom-renderer-extjs-grid" width="652" height="302" class="aligncenter size-full wp-image-358" /></p>
<p>You can also add images in grid in this way. Try replacing Gender in this example with appropriate icons. I leave this as an exercise for you.</p>
<p><a href='http://www.dottostring.com/wp-content/uploads/2009/04/dottostring-extjs-grid-fields.zip'>Download the example code</a></p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fwww.dottostring.com%2F2009%2F04%2Fadding-support-for-net-datatypes-to-extjs-grid-datetime-boolean-and-currency%2F';
  addthis_title  = 'Adding+support+for+.NET+datatypes+to+ExtJs+Grid+%28DateTime%2C+Boolean+and+Currency%29';
  addthis_pub    = 'erfaan';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
]]></content:encoded>
			<wfw:commentRss>http://www.dottostring.com/2009/04/adding-support-for-net-datatypes-to-extjs-grid-datetime-boolean-and-currency/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>On-Demand Paging using ExtJS Grid with Client-Centric ASP.NET AJAX (WebMethods)</title>
		<link>http://www.dottostring.com/2008/12/on-demand-paging-using-extjs-grid-with-client-centric-asp-dot-net-ajax-webmethods/</link>
		<comments>http://www.dottostring.com/2008/12/on-demand-paging-using-extjs-grid-with-client-centric-asp-dot-net-ajax-webmethods/#comments</comments>
		<pubDate>Thu, 18 Dec 2008 00:51:03 +0000</pubDate>
		<dc:creator>Irfan</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[ExtJs]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Client Centric]]></category>
		<category><![CDATA[grid]]></category>
		<category><![CDATA[javscript]]></category>
		<category><![CDATA[On Demand Paging]]></category>
		<category><![CDATA[Web Method]]></category>

		<guid isPermaLink="false">http://www.dottostring.com/?p=181</guid>
		<description><![CDATA[We have a scenario where we want to use on demand paging for ExtJS grid using some smart AJAX techniques. One method could be to use default functionality of ExtJS grid with ExtJS PagingToolbar in its bottom bar; and ExtJS store associated with this grid is using httpProxy to fetch data. This httpProxy requires a url of [...]]]></description>
			<content:encoded><![CDATA[<p>We have a scenario where we want to use on demand paging for ExtJS grid using some smart AJAX techniques. One method could be to use default functionality of ExtJS grid with ExtJS PagingToolbar in its bottom bar; and ExtJS store associated with this grid is using httpProxy to fetch data. This httpProxy requires a url of aspx page only and it will fetch data from this page. This seems quite easy but there are some issues with this technique. We dont want the Page_Load method to be called every time creating a complete page on server side. Other way is to use WebMethods which are quite efficient. But ExtJS has no proxy for Page Methods. In this tutorial we will be creating a PageMethodProxy extended from DataProxy of ExtJS and will use it with JsonStore of ExtJS. Lets start:</p>
<div id="attachment_190" class="wp-caption aligncenter" style="width: 417px"><img class="size-full wp-image-190" title="EXTJS-ASP-NET-ON-DEMAND-PAGING" src="http://www.dottostring.com/wp-content/uploads/2008/12/extjs-asp-net-paging.jpg" alt="An Illustration of On-Demand Paging Using EXTJS Grid and ASP.NET" width="407" height="304" /><p class="wp-caption-text">An Illustration of On-Demand Paging Using EXTJS Grid and ASP.NET</p></div>
<p>Lets start by creating a PageMethod which takes page index and number of required results on a page as parameter and returns an object of ProductList type.</p>
<pre name="code" class="c#">using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Text;
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    /// &lt;summary&gt;
    /// This method will be called from the client side using PageMethods
    /// and its primary responsibility is to fetch records from the database
    /// using that startRowIndex and MaximumRows allowed
    /// &lt;/summary&gt;
    /// &lt;param name="PageNumber"&gt;Page Number of the grid&lt;/param&gt;
    /// &lt;param name="MaximumRows"&gt;Page Size&lt;/param&gt;
    /// &lt;returns&gt;Rows in the form of a list&lt;/returns&gt;
    [System.Web.Services.WebMethod]
    public static ProductList GetProducts(int PageNumber,int MaximumRows)
    {
        //calculating the start row index
        int Start = PageNumber + 1;
        //calculating the end row index
        int End = PageNumber + MaximumRows;
        ProductList productList = new ProductList();
        //setting up sql connection to execute the query
        SqlConnection sqlConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
        sqlConnection.Open();
        //setting up the command object with a parameterized query and sql connection
        using (SqlCommand command = new SqlCommand(GetQuery(), sqlConnection))
        {
            //Creating Sql Start Paramter
            SqlParameter StartParameter = new SqlParameter();
            StartParameter.DbType = DbType.Int32;
            StartParameter.ParameterName = "startRowIndex";
            StartParameter.Value = Start;
            //Creating Sql End Parameter
            SqlParameter EndParameter = new SqlParameter();
            EndParameter.DbType = DbType.Int32;
            EndParameter.ParameterName = "endRowIndex";
            EndParameter.Value = End;
            //Adding Start Parameter to the command object
            command.Parameters.Add(StartParameter);
            //Adding End Parameter to the command object
            command.Parameters.Add(EndParameter);
            //Executing Reader
            using (IDataReader reader = command.ExecuteReader())
            {
                //Creating a list of objects from the fetched rows
                while (reader.Read())
                {
                    productList.lstProducts.Add(ConstructProduct(reader));
                }
            }
        }
        //closing the connection
        sqlConnection.Close();
        //Assigning total row count for the given query so that it can
        //be used by the grid to set up total number of pages
        productList.RowCount = GetRowCount();
        return productList;
    }
    /// &lt;summary&gt;
    /// Builds the Actual Parameterized Query which handles On-Demand Paging using
    /// ROW_NUMBER() feature given by SQL Server 2005
    /// &lt;/summary&gt;
    /// &lt;returns&gt;Parameterized Query&lt;/returns&gt;
    private static String GetQuery()
    {

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.Append(" SELECT * FROM ( ");
        stringBuilder.Append(" SELECT	ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS row_num,ProductID,[Name],ProductNumber,SafetyStockLevel,ReorderPoint ");
        stringBuilder.Append(" FROM	Product ");
        stringBuilder.Append(" ) AS TempTable WHERE row_num&gt;=@startRowIndex AND row_num&lt;=@endRowIndex ");
        return stringBuilder.ToString();
    }
    /// &lt;summary&gt;
    /// Builds the Query such that it return the count of the
    /// total number of account the query will select without
    /// paging
    /// &lt;/summary&gt;
    /// &lt;returns&gt;Query to return total number of records&lt;/returns&gt;
    private static String GetRowCountQuery()
    {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.Append(" SELECT COUNT(*) FROM ( ");
        stringBuilder.Append(" SELECT	ProductID,[Name],ProductNumber,SafetyStockLevel,ReorderPoint ");
        stringBuilder.Append(" FROM	Product ");
        stringBuilder.Append(" ) AS TempTable");
        return stringBuilder.ToString();
    }
    /// &lt;summary&gt;
    /// Executes the Actual Query without paging in order to
    /// fetch total number of records
    /// &lt;/summary&gt;
    /// &lt;returns&gt;Total Number of records&lt;/returns&gt;
    private static int GetRowCount()
    {
        int rowCount;
        SqlConnection sqlConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
        sqlConnection.Open();
        using (SqlCommand command = new SqlCommand(GetRowCountQuery(), sqlConnection))
        {
            rowCount = Convert.ToInt32(command.ExecuteScalar());
        }
        sqlConnection.Close();
        return rowCount;

    }
    /// &lt;summary&gt;
    /// Constructs Product Entity from the IDataReaer
    /// &lt;/summary&gt;
    /// &lt;param name="reader"&gt;Reader (Already Executed)&lt;/param&gt;
    /// &lt;returns&gt;Product Entity&lt;/returns&gt;
    private static Product ConstructProduct(IDataReader reader)
    {
        Product product = new Product();

        int i = reader.GetOrdinal("ProductID");
        if (!reader.IsDBNull(i))
            product.ProductID = reader.GetInt32(i);
        i = reader.GetOrdinal("Name");
        if (!reader.IsDBNull(i))
            product.Name = reader.GetString(i);
        i = reader.GetOrdinal("ProductNumber");
        if (!reader.IsDBNull(i))
            product.ProductNumber = reader.GetString(i);
        i = reader.GetOrdinal("SafetyStockLevel");
        if (!reader.IsDBNull(i))
            product.SafetyStockLevel = Convert.ToInt32(i);
        i = reader.GetOrdinal("ReorderPoint");
        if (!reader.IsDBNull(i))
            product.ReorderPoint = Convert.ToInt32(i);

        return product;
    }
}</pre>
<p>Now we include our magical PageMethodProxy on our page.</p>
<pre name="code" class="js">Ext.data.PageMethodProxy = function(config){
	Ext.data.PageMethodProxy.superclass.constructor.call(this);
	Ext.apply(this, config);
};

Ext.data.PageMethodProxy.TRANS_ID = 1000;
Ext.data.PageMethodProxy.arr_trans = Array();

Ext.extend(Ext.data.PageMethodProxy, Ext.data.DataProxy, {
    load : function(params, reader, callback, scope, arg) {
        if(this.fireEvent("beforeload", this, params) !== false){

            var p = Ext.apply(params, this.extraParams);

            var transId = ++Ext.data.PageMethodProxy.TRANS_ID;
            var trans = {
                id : transId,
                params : params,
                arg : arg,
                callback : callback,
                scope : scope,
                reader : reader
            };

            eval("PageMethods." + this.pageMethod + "(p.start,p.limit,this.handleResponse)");

            Ext.data.PageMethodProxy.arr_trans[Ext.data.PageMethodProxy.TRANS_ID] = trans;
        }
        else{
            callback.call(scope||this, null, arg, false);
        }

    },	

    isLoading : function(){
        return this.trans ? true : false;
    },

    abort : function(){
        if(this.isLoading()){
            this.destroyTrans(this.trans);
        }
    },

    handleResponse : function(o){
        var trans = Ext.data.PageMethodProxy.arr_trans[Ext.data.PageMethodProxy.TRANS_ID];
        var result;
        try {
            result = trans.reader.readRecords(o);
        }catch(e){
            this.fireEvent("loadexception", this, o, trans.arg, e);
            trans.callback.call(trans.scope||window, null, trans.arg, false);
            return;
        }
        this.trans = false;
        trans.callback.call(trans.scope||window, result, trans.arg, true);
    }
});</pre>
<p>You should have following three Javascripts on your page.</p>
<pre name="code" class="html">&lt;script type="text/javascript" src="extjs/adapter/ext/ext-base.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="extjs/ext-all-debug.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="extjs/pagemethods-proxy.js"&gt;&lt;/script&gt;</pre>
<p>We start by making an object of our PageMethodProxy in Ext.onReady</p>
<pre name="code" class="js">Ext.onReady(function(){
    // lets make an object of pagemethod proxy first
    var pmProxy = new Ext.data.PageMethodProxy({
	    pageMethod: 'GetProducts'
    });
});</pre>
<p>Now we make a JsonStore which uses the object of this proxy and specifies properties of Json.</p>
<pre name="code" class="js">Ext.onReady(function(){
    // lets make an object of pagemethod proxy first
    var pmProxy = new Ext.data.PageMethodProxy({
	    pageMethod: 'GetProducts'
    });

    // create the Data Store
    var store = new Ext.data.JsonStore({
        root: 'lstProducts',
        totalProperty: 'RowCount',
        idProperty: 'ProductID',
	    fields: [
            'Name','ProductID', 'ProductNumber', 'ReorderPoint','SafetyStockLevel'
        ],
        proxy:pmProxy
    });
});</pre>
<p>Make a PagingToolbar object to be used in grid.</p>
<pre name="code" class="js">Ext.onReady(function(){
    // lets make an object of pagemethod proxy first
    var pmProxy = new Ext.data.PageMethodProxy({
	    pageMethod: 'GetProducts'
    });

    // create the Data Store
    var store = new Ext.data.JsonStore({
        root: 'lstProducts',
        totalProperty: 'RowCount',
        idProperty: 'ProductID',
	    fields: [
            'Name','ProductID', 'ProductNumber', 'ReorderPoint','SafetyStockLevel'
        ],
        proxy:pmProxy
    });

    // create paging bar
    var pagingBar = new Ext.PagingToolbar({
        pageSize: 10,
        store: store,
        emptyMsg: "No topics to display"
    });
});</pre>
<p>At the end create a grid placeholder div and create the grid object.</p>
<pre name="code" class="js">Ext.onReady(function(){
    // lets make an object of pagemethod proxy first
    var pmProxy = new Ext.data.PageMethodProxy({
	    pageMethod: 'GetProducts'
    });

    // create the Data Store
    var store = new Ext.data.JsonStore({
        root: 'lstProducts',
        totalProperty: 'RowCount',
        idProperty: 'ProductID',
	    fields: [
            'Name','ProductID', 'ProductNumber', 'ReorderPoint','SafetyStockLevel'
        ],
        proxy:pmProxy
    });

    // create paging bar
    var pagingBar = new Ext.PagingToolbar({
        pageSize: 10,
        store: store,
        emptyMsg: "No topics to display"
    });

    // create the grid
    var grid = new Ext.grid.GridPanel({
        el:'grid-products',
        width:405,
        height:300,
        title:'Adventure Works Products',
        store: store,
        stripeRows: true,
        loadMask: true,
        enableHdMenu: false,

        // grid columns
        columns:[{
    	    header: "id",
    	    id: 'ProductID',
            dataIndex: 'ProductID',
            hidden:true
        },{
            header: "Product Name",
            dataIndex: 'Name',
            width: 200
        },{
            header: "Product Number",
            dataIndex: 'ProductNumber',
            width: 100
        },{
            header: "Safety Stock Level",
            dataIndex: 'SafetyStockLevel',
            width: 100
        }],
        // put paging bar on the bottom
        bbar: pagingBar
    });

    grid.render();

    // set parameters for initial loading
    store.load({
	    params:{
		    start:0,
		    limit:10
	    }
    });
});</pre>
<ul>
<li>And thats all <img src='http://www.dottostring.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
<li>Cheers, don&#8217;t forget to leave comments/feedback</li>
<li>Download Source Code <a href="http://www.dottostring.com/wp-content/uploads/2008/12/dottostringon-demand-paging-ext-js-asp-net.zip" target="_blank">Here</a></li>
</ul>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fwww.dottostring.com%2F2008%2F12%2Fon-demand-paging-using-extjs-grid-with-client-centric-asp-dot-net-ajax-webmethods%2F';
  addthis_title  = 'On-Demand+Paging+using+ExtJS+Grid+with+Client-Centric+ASP.NET+AJAX+%28WebMethods%29';
  addthis_pub    = 'erfaan';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
]]></content:encoded>
			<wfw:commentRss>http://www.dottostring.com/2008/12/on-demand-paging-using-extjs-grid-with-client-centric-asp-dot-net-ajax-webmethods/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>
