Export to Excel or PDF in RadGrid


RadGrid has a built-in facility to export the grid’s data into different formats like Excel, CSV, Word or PDF and we can export the same as per the system requierement. Here I will show you how to export grid’s data in PDF or Excel format.


First of all in RadGrid, place the ExportSettings tag as below in the code. Here I have set properties like IgnorePaging equal to True to export all grids data and OpenInNewWindow equal to true to open the export data in a seperate window. Also in ExportSettings section I have defined the width of the PDF page.




Now in RadAjaxManager of your page add the following event:


Then, add the following javascript function in your aspx page:

function requestStart(sender, args) {

if (args.get_eventTarget().indexOf(“btnExportToPDF”) > 0 ||

args.get_eventTarget().indexOf(“btnExportToExcel”) > 0)



And then add the command name for the button as like following for PDF or Excel.


and it’s done.



RadGrid supports grouping of items based on the value of a particular column. You can even have multilevel grouping based on different criteria.

To group the data in a grid, specify grouping criteria by setting the GroupByExpressions property of a table view in the grid


<MasterTableView Width=”100%” CommandItemDisplay=”Top” GroupLoadMode=”Server” ShowGroupFooter=”true”>




<telerik:GridGroupByField FieldAlias=”Security” FieldName=”SEC_CODE” SortOrder=”Ascending” />



<telerik:GridGroupByField FieldAlias=”Security” FieldName=”SEC_CODE” SortOrder=”Ascending” />





Change RadGrid PageSize Dropdown


Telerik’s RadGrid provides in-built functionality for paging. User have to select the number of records from the Page Size combo box (default is 10, 20 and 50) and selected number of records is going to display in RadGrid. But we can also change the Page Size in combo box as per our requirement. Following is the code to do the same:


protectedvoid grdViewReport_ItemDataBound(object sender, GridItemEventArgs e)


if (e.Item isGridPagerItem)


RadComboBox PageSizeCombo = (RadComboBox)e.Item.FindControl(“PageSizeComboBox”);



PageSizeCombo.FindItemByText(“100”).Attributes.Add(“ownerTableViewId”, grdViewReport.MasterTableView.ClientID);


PageSizeCombo.FindItemByText(“200”).Attributes.Add(“ownerTableViewId”, grdViewReport.MasterTableView.ClientID);


PageSizeCombo.FindItemByText(“500”).Attributes.Add(“ownerTableViewId”, grdViewReport.MasterTableView.ClientID);

PageSizeCombo.FindItemByText(e.Item.OwnerTableView.PageSize.ToString()).Selected = true;



Extension methods in c#

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable<T> types. To use the standard query operators, first bring them into scope with a using System.Linq directive. Then any type that implements IEnumerable<T> appears to have instance methods such as GroupBy, OrderBy, Average, and so on. You can see these additional methods in IntelliSense statement completion when you type “dot” after an instance of an IEnumerable<T> type such as List<T> or Array.

The following example shows how to call the standard query operator OrderBy method on an array of integers. The expression in parentheses is a lambda expression. Many standard query operators take lambda expressions as parameters, but this is not a requirement for extension methods. For more information, see Lambda Expressions (C# Programming Guide).

class ExtensionMethods2    
    static void Main()
        int[] ints = { 10, 45, 15, 39, 21, 26 };
        var result = ints.OrderBy(g => g);
        foreach (var i in result)
            System.Console.Write(i + " ");
//Output: 10 15 21 26 39 45

Extension methods are defined as static methods but are called by  using instance method syntax. Their first parameter specifies which type  the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
The following example shows an extension method defined for the System.String class. Note that it is defined inside a non-nested, non-generic static class:
namespace ExtensionMethods
    public static class MyExtensions
        public static int WordCount(this String str)
            return str.Split(new char[] { ' ', '.', '?' }, 
The WordCount extension method can be brought into scope with this using directive:
using ExtensionMethods;
And it can be called from an application by using this syntax:
string s = "Hello Extension Methods";
int i = s.WordCount();
In your code you invoke the extension method with instance method syntax. However, the intermediate language (IL) generated by the compiler translates your code into a call on the static method. Therefore, the principle of encapsulation is not really being violated. In fact, extension methods cannot access private variables in the type they are extending.
For more information, see How to: Implement and Call a Custom Extension Method (C# Programming Guide).
In general, you will probably be calling extension methods far more often than implementing your own. Because extension methods are called by using instance method syntax, no special knowledge is required to use them from client code. To enable extension methods for a particular type, just add a using directive for the namespace in which the methods are defined. For example, to use the standard query operators, add this using directive to your code:
using System.Linq;
(You may also have to add a reference to System.Core.dll.) You will  notice that the standard query operators now appear in IntelliSense as  additional methods available for most IEnumerable<T> types.

Binding Extension Methods at Compile Time  

You can use extension methods to  extend a class or interface, but not to override them. An extension  method with the same name and signature as an interface or class method  will never be called. At compile time, extension methods always have  lower priority than instance methods defined in the type itself. In  other words, if a type has a method named Process(int i),  and you have an extension method with the same signature, the compiler  will always bind to the instance method. When the compiler encounters a  method invocation, it first looks for a match in the type's instance  methods. If no match is found, it will search for any extension methods  that are defined for the type, and bind to the first extension method  that it finds. The following example demonstrates how the compiler  determines which extension method or instance method to bind to.


The following example  demonstrates the rules that the C# compiler follows in determining  whether to bind a method call to an instance method on the type, or to  an extension method. The static class Extensions contains extension methods defined for any type that implements IMyInterface. Classes A, B, and C all implement the interface.
The MethodB extension method is never called because its name and signature exactly match methods already implemented by the classes. 
When the compiler cannot find an  instance method with a matching signature, it will bind to a matching  extension method if one exists.
// Define an interface named IMyInterface.
namespace DefineIMyInterface
    using System;
    public interface IMyInterface
        // Any class that implements IMyInterface must define a method
        // that matches the following signature.
        void MethodB();
// Define extension methods for IMyInterface.
namespace Extensions
    using System;
    using DefineIMyInterface;
    // The following extension methods can be accessed by instances of any 
    // class that implements IMyInterface.
    public static class Extension
        public static void MethodA(this IMyInterface myInterface, int i)
                ("Extension.MethodA(this IMyInterface myInterface, int i)");
        public static void MethodA(this IMyInterface myInterface, string s)
                ("Extension.MethodA(this IMyInterface myInterface, string s)");
        // This method is never called in ExtensionMethodsDemo1, because each 
        // of the three classes A, B, and C implements a method named MethodB
        // that has a matching signature.
        public static void MethodB(this IMyInterface myInterface)
                ("Extension.MethodB(this IMyInterface myInterface)");
// Define three classes that implement IMyInterface, and then use them to test
// the extension methods.
namespace ExtensionMethodsDemo1
    using System;
    using Extensions;
    using DefineIMyInterface;
    class A : IMyInterface
        public void MethodB() { Console.WriteLine("A.MethodB()"); }
    class B : IMyInterface
        public void MethodB() { Console.WriteLine("B.MethodB()"); }
        public void MethodA(int i) { Console.WriteLine("B.MethodA(int i)"); }
    class C : IMyInterface
        public void MethodB() { Console.WriteLine("C.MethodB()"); }
        public void MethodA(object obj)
            Console.WriteLine("C.MethodA(object obj)");
    class ExtMethodDemo
        static void Main(string[] args)
            // Declare an instance of class A, class B, and class C.
            A a = new A();
            B b = new B();
            C c = new C();
            // For a, b, and c, call the following methods:
            //      -- MethodA with an int argument
            //      -- MethodA with a string argument
            //      -- MethodB with no argument.
            // A contains no MethodA, so each call to MethodA resolves to 
            // the extension method that has a matching signature.
            a.MethodA(1);           // Extension.MethodA(object, int)
            a.MethodA("hello");     // Extension.MethodA(object, string)
            // A has a method that matches the signature of the following call
            // to MethodB.
            a.MethodB();            // A.MethodB()
            // B has methods that match the signatures of the following
            // nethod calls.
            b.MethodA(1);           // B.MethodA(int)
            b.MethodB();            // B.MethodB()
            // B has no matching method for the following call, but 
            // class Extension does.
            b.MethodA("hello");     // Extension.MethodA(object, string)
            // C contains an instance method that matches each of the following
            // method calls.
            c.MethodA(1);           // C.MethodA(object)
            c.MethodA("hello");     // C.MethodA(object)
            c.MethodB();            // C.MethodB()
/* Output:
    Extension.MethodA(this IMyInterface myInterface, int i)
    Extension.MethodA(this IMyInterface myInterface, string s)
    B.MethodA(int i)
    Extension.MethodA(this IMyInterface myInterface, string s)
    C.MethodA(object obj)
    C.MethodA(object obj)

General Guidelines

In general, we recommend that  you implement extension methods sparingly and only when you have to.  Whenever possible, client code that must extend an existing type should  do so by creating a new type derived from the existing type. For more  information, see Inheritance (C# Programming Guide). 

When using an extension method  to extend a type whose source code you cannot change, you run the risk  that a change in the implementation of the type will cause your  extension method to break. 
If you do implement extension methods for a given type, remember the following two points:  

1) An extension method will never be called if it has the same signature as a method defined in the type.  

2)Extension methods are brought into scope at the namespace level.  For example, if you have multiple static classes that contain extension  methods in a single namespace named Extensions, they will all be brought into scope by the using Extensions; directive.



When we create our application using LINQ, in that case we have to write all SQL queries using LINQ query operators. And it is a general requirement to write GROUP BY query when we try to build reports in our application in most cases.


Following is the code or Query example to write GROUP BY Query in LINQ to Entities or Entity Framework:

var objData = from f in DASEntity.FILES
from s in DASEntity.STATUS
where f.ID == fr.FILE_ID
&& fr.STATUS_ID == s.ID
&& f.CLIENT_TOKEN == ClientToken
&& fr.CLIENT_TOKEN == ClientToken
group s by new { s.ID, s.NAME } into t
select new
StatusID = t.Key.ID,
Name = t.Key.NAME,
FileCount = t.Count()

Firefox and the FileUpload control in ASP.NET

I’ve been pretty annoyed about the fact that FireFox ignores the width property of the ASP.NET FileUpload control. It doesn’t matter if you set it by CSS or even in JavaScript, Firefox always ignores it and that results in a crippled layout since you have no control over the width of the upload input field. This actually has nothing to do with the FileUpload control, but with the rendered output of that control, which is just a standard field.

Here the width is set to 400px. The FileUpload control renders the Width attribute to the correct CSS style value of 400px at runtime.

FileUpload runat=”server” ID=”txtUpload” Width=”400″ />

But as mentioned, Firefox totally ignores that. Then I remembered a forum thread I read some years ago about a size attribute. The only thing I could find was this list of available HTML attributes, but I gave it a try.

This is what I ended up with. The size attribute actually works in Firefox and IE ignores it, but adheres to the Width attribute instead.

FileUpload runat=”server” ID=”txtUpload” Width=”400″ size=”50″ />

The size attribute determines the number of characters should be visible and then adjusts the width accordingly. It is not the same as setting a maximum length of the file name, so it doesn’t break anything.

You should think that since a size of 50 generates the same width as 400px that you could always just divide the width in pixels with 8 to find the equivalent size. That is not the case. You have to manually adjust every time until you find the right size value that matches the pixel width

Tricks to increase SQL Server query performance

Thanks to the natural language roots of the SQL language, writing queries has become extremely easy for just about anyone to pick up. But its simplicity also makes it easy to write poorly performing queries. Here are some simple changes you can make to improve not only query performance, but, in some cases, overall SQL Server system performance as well.


Oftentimes, within stored procedures or other SQL scripts, temp tables must be created and loaded with data. When writing these queries, many SQL Server DBAs and developers like to use the SELECT INTO method, like this:

INTO #TempTable
FROM sysobjects

While this technique works fine for small tables, when dealing with large record sets or long-running queries, it creates locks on the system objects within the tempdb database. As a result, other queries and procedures that need to create objects within the tempdb database will have to wait for the long-running query to complete. This is because when an object is created, an exclusive lock is taken against the sysobjects, syscolumns, sysindexes, etc system tables (SQL Server 2000) or the sysallocunits, syscolpars, syshobtcolumns, sysschobjs, sysserefs, etc system tables (SQL Server 2005). You can see this easily by opening two query windows and running the following:

(First window)
begin tran
create table #test1 (c1 int)
(Second window SQL 2005)
select object_name(rsc_objid), *
from sys.syslockinfo
where req_spid = 52 /*Where 52 = the SPID of the first window*/
order by 1

(Second window SQL Server 2000)
sp_lock 52 /*Where 52 = the SPID of the first window*/

When you have a very long-running query in a temporary table using the SELECT INTO format, those same system table locks are held until the query completes and data loads into the temp table. You can avoid system table locking by manually creating the table with the CREATE TABLE command—before loading the data into the table.
For example, this code…

(spid int)
FROM sys.objects

…will require much less locking than this code:

INTO #TempTable
FROM sys.objects

While the total number of locks taken is the same, the length of time the locks are held for the first query will be much shorter. This allows other processes to create temp tables.
Typically, when developing SQL code the development server has only a single user or few users. When working on SQL code, it’s important to know when the code will impact sessions other than the current session. And unexpected interaction can cause major performance issues.

Accessing data across linked servers

Linked servers are an excellent way to get data in real-time from one server to another. However, incorrectly written linked server queries can quickly decrease system performance on one or both servers. While it’s easy to write these queries across linked servers, the query optimizer doesn’t always work as you would expect. I often see queries that join a local table to two remote tables and the queries take hours to run. That’s because the local optimizer doesn’t know which records to request from the remote table.
It therefore requests that the remote server transmit the entire table, and all that data is then loaded into a temporary table and the join is done locally. Unfortunately, because the local table is a temporary table—and not a physical table on the source system—the indexes on the remote table do not get created on the temporary table. Because of the lack of indexes, expected query execution time skyrockets.

There are a couple of techniques you can use to improve query response time. The first is to create a stored procedure on the remote database and have it return a record set, being a subset of the remote tables, which is then loaded into a local temporary table. It can then be indexed as needed. The trick with this method is to provide an input variable to the remote procedure where input values can be passed to. Thus, you will reduce the number of returned records by as much as possible. Fewer records will reduce the run time of that stored procedure as well as
the network latency on transferring those records from the remote system to the local system.
The second technique you can use is a variation of the first method. You create local temporary tables for each of the remote tables and transfer over the columns and records needed from each of the remote tables. Next, index the tables as needed and join the temp tables locally.
While the second technique is easier and faster to set up and implement, the first method gives you a greater performance savings, as typically less data needs to be transferred between servers.

Subqueries as join partners

When working with joins, you may want to manually control the order that data is selected. An easy (and usually safe) way to do this is to use subqueries as the join object instead of joining directly to a table. In some instances, you can decrease your query execution time by forcing the SQL Server to prefilter data in the table. This method is not foolproof and if used incorrectly it can increase the execution time of your query. The method should be fully tested before moving it to your production environment.

As we have seen, there are some quick and easy methods for improving query performance for some long-running processes. While these techniques will not apply to every issue you run across, they will help in some instances.

Simple way to Show/Hide Filter in RadGrid


Telerik’s RadGrid provides in-built search functionality. You can find the search functionality at top of the grid just below the header columns. But user should be able to hide the same to save unnecessary space all the time from the grid.

RadGrid Example when Filter is not visible to the user:

Radgrid without Filter

Radgrid without Filter

RadGrid Example when Filter is visible to the user:

RadGrid With Filter

RadGrid With Filter


First of all in RadGrid’s MasterTableView tag, add following checkbox:

<MasterTableView Width=”100%” CommandItemDisplay=”Top” GroupLoadMode=”Server”>


<asp:CheckBox ID=”CheckBox2″ AutoPostBack=”true” CssClass=”CheckBox” runat=”server”

ForeColor=”White” Text=”Show Filter” />


After that add the ItemCreated event in the RadGrid as following code does:

protected void grdManageTransType_ItemCreated(object sender, GridItemEventArgs e)


if (e.Item.ItemType == GridItemType.CommandItem)


GridCommandItem commandItem = e.Item as GridCommandItem;

CheckBox chkFilter2 = (CheckBox)commandItem.FindControl(“CheckBox2”);

chkFilter2.AutoPostBack = true;

chkFilter2.ForeColor = System.Drawing.Color.White;

chkFilter2.Checked = grdManageTransType.AllowFilteringByColumn;

//Adding the event handler

chkFilter2.CheckedChanged += new EventHandler(chkFilter2_CheckedChanged);


if (e.Item.ItemType == GridItemType.SelectedItem)

e.Item.BackColor = Color.FromName(“#FFEDC1”);


In above portion of code we are creating CheckedChanged event of the checkbox. So now create the CheckedChanged event of the checkbox as per following code:

protected void chkFilter2_CheckedChanged(object sender, EventArgs e)


grdManageTransType.AllowFilteringByColumn = !grdManageTransType.AllowFilteringByColumn;



As per the above code portions, we can the checkbox at the top of the RadGrid. On click of that checkbox RadGrid’s filter should be visible on or off.

Count items in Telerik’s RadComboBox


It is general requirement to show and count number of items in Telerik’s RadComboBox. And we can do that by using a simple javascript function.


In javasript:

function UpdateItemCountField(sender, args) {

//set the footer text

sender.get_dropDownElement().lastChild.innerHTML = “A total of “ + sender.get_items().get_count() + ” items”;


In aspx page:

add footer template as shown below code.


A total of

<asp:Literal runat=”server” ID=”RadComboItemsCount” />



Compare two data tables in c#


Comparing two datatable and get the final table with difference in it, this kind of requirement is generally arise generally when we are doing multiple insert or update. I have scenario like get the two different tables data, compare it and if there is difference in output then insert that data into the third table. So use the approach to get the data from database into different table and then insert the difference output using SqlBulkCopy in to the third table.



Following is the code to compare two datatable. Just copy and paste this class into your code and its working.


using System;

using System.Data;


namespace [Namespace Name]


public class CompareDataTables


public static DataTable CompareTables(DataTable first, DataTable second)


first.TableName = “FirstTable”;

second.TableName = “SecondTable”;


//Create Empty Table

DataTable table = new DataTable(“Difference”);




//Must use a Dataset to make use of a DataRelation object

using (DataSet ds = new DataSet())


//Add tables

ds.Tables.AddRange(new DataTable[] { first.Copy(), second.Copy() });


//Get Columns for DataRelation

//DataColumn[] firstcolumns = new DataColumn[ds.Tables[0].Columns.Count];

DataColumn[] firstcolumns = new DataColumn[2];

firstcolumns[0] = ds.Tables[0].Columns[1];

firstcolumns[1] = ds.Tables[0].Columns[7];


//for (int i = 0; i < firstcolumns.Length; i++)


// firstcolumns[i] = ds.Tables[0].Columns[i];



//DataColumn[] secondcolumns = new DataColumn[ds.Tables[1].Columns.Count];

DataColumn[] secondcolumns = new DataColumn[2];

secondcolumns[0] = ds.Tables[1].Columns[1];

secondcolumns[1] = ds.Tables[1].Columns[7];


//for (int i = 0; i < secondcolumns.Length; i++)


// secondcolumns[i] = ds.Tables[1].Columns[i];



//Create DataRelation

DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);




//Create columns for return table

for (int i = 0; i < first.Columns.Count; i++)


table.Columns.Add(first.Columns[i].ColumnName, first.Columns[i].DataType);



//If First Row not in Second, Add to return table.



foreach (DataRow parentrow in ds.Tables[0].Rows)


DataRow[] childrows = parentrow.GetChildRows(r);

if (childrows == null || childrows.Length == 0)

table.LoadDataRow(parentrow.ItemArray, true);







catch (Exception ex)


throw ex;



return table;





Code Explanation:


  1. CompareTables method is static, so you can call it directly from your class. Just add the appropriate reference.
  2. Pass the two data tables in this method.
  3. Then creates the dataset.
  4. Add two tables into the dataset.
  5. Then important part, define the columns two compare the data table. In my case i just want to check the column 1 & 7. If there is a mismatch between this two then inserts the record. You can modify the code as per your requirement or just uncomment the line above and below my code , which adds all columns.
  6. Creates data relation on that column(s).
  7. Add relation two the dataset.
  8. Create the target or difference table colums
  9. Then load the difference data in it and return the difference table.