Monday, December 19, 2011

Merging Gridview with Multiple Headers

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    #region Declarations
    CustomersDataObject objData = null;
    GridViewRow HeaderRow = null;
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            objData = new CustomersDataObject();
            //DataTable dt =  objData.Select().Table ;
            gvStylish.DataSource = objData.Select();
            gvStylish.DataBind();
        }
    }

    protected void gvStylish_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //http://www.codeproject.com/Articles/249155/Rows-and-Columns-Merging-in-ASP-NET-GridView-Contr
        //http://sammisoft.net/mboard/mboard/mboard.asp?exe=view&board_id=pds&group_name=sammisoft&idx_num=194&page=22&category=0&search_category=&search_word=&order_c=intVote&order_da=asc
        //http://www.thaicreate.com/dotnet/forum/048135.html

        if (e.Row.RowType == DataControlRowType.Header)
        {
            GridView HeaderGrid = (GridView)sender;
            HeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
            for (int cellCount = 0; cellCount < e.Row.Cells.Count; cellCount++)
            {
                if (e.Row.Cells[cellCount].Text.Trim() == "CustomerID"
                    || e.Row.Cells[cellCount].Text.Trim() == "CompanyName"
                    || e.Row.Cells[cellCount].Text.Trim() == "ContactName")
                {
                    //Row Span
                    HeaderRow.Cells.Add(HeaderRowMerg(e, 2, cellCount, System.Drawing.Color.Gray.Name));
                }

                else
                {
                    //Col Span
                    HeaderRow.Cells.Add(HeaderColumnMerg(e, 3, "Subjects", System.Drawing.Color.Gray.Name));
                    break;
                }

            }
            gvStylish.Controls[0].Controls.AddAt(0, HeaderRow);
        }
    }

    /// 
    /// Merging datarow cells
    /// 
    /// /// protected void gvStylish_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            /*Merging starts*/
            int _iNoOfCellsToCheck = 6;
            for (int rowIndex = gvStylish.Rows.Count - 2; rowIndex >= 0; rowIndex--)
            {
                GridViewRow gvRow = gvStylish.Rows[rowIndex];
                GridViewRow gvPreviousRow = gvStylish.Rows[rowIndex + 1];
                //for (int cellCount = 0; cellCount < gvRow.Cells.Count; cellCount++)
                for (int cellCount = 1; cellCount < _iNoOfCellsToCheck; cellCount++)
                {
                    if (gvRow.Cells[cellCount].Text == gvPreviousRow.Cells[cellCount].Text)
                    {
                        gvRow.Cells[cellCount].RowSpan =
                            gvPreviousRow.Cells[cellCount].RowSpan < 2 ?
                            2 :
                            gvPreviousRow.Cells[cellCount].RowSpan + 1;

                        gvPreviousRow.Cells[cellCount].Visible = false;
                    }
                }
            }
            /*Merging ends*/

            //If we want to set background color for the row
            //if (e.Row.Cells[0].Text.Trim().ToUpper().Contains("TOTAL"))
            if (e.Row.Cells[0].Text.Trim().ToUpper().Contains("MUTHU"))
            {

                SetRowBackColor(e, System.Drawing.Color.Silver.Name);
            }
            else
                //if (e.Row.Cells[0].Text.Trim().ToUpper().Contains("GRAND"))
                if (e.Row.Cells[0].Text.Trim().ToUpper().Contains("VIJAY"))
                {
                    SetRowBackColor(e, "#999999");
                }
        }
    }
    #endregion

    #region Functions
    private TableCell HeaderRowMerg(GridViewRowEventArgs e, int iRowSpan, int iIndex, string backcolor)
    {
        TableHeaderCell Cell_Header = new TableHeaderCell();
        Cell_Header.Text = e.Row.Cells[iIndex].Text;
        Cell_Header.HorizontalAlign = HorizontalAlign.Center;
        Cell_Header.Font.Bold = true;
        Cell_Header.RowSpan = iRowSpan;
        Cell_Header.Style.Add("background-color", backcolor);
        e.Row.Cells[iIndex].Attributes.Add("style", "display: none;");
        return Cell_Header;
    }

    private TableCell HeaderColumnMerg(GridViewRowEventArgs e, int iColumnSpan, string _strHeaderText, string backcolor)
    {
        TableHeaderCell cell = new TableHeaderCell();
        Cell_Header.Text = _strHeaderText;
        Cell_Header.HorizontalAlign = HorizontalAlign.Center;
        Cell_Header.ColumnSpan = iColumnSpan;
        Cell_Header.Font.Bold = true;
        Cell_Header.Style.Add("background-color", backcolor);
        return Cell_Header;
    }

    bool IsInt(string strVal)
    {
        try
        {
            int value = int.Parse(strVal);
            return true;
        }
        catch
        {
            return false;
        }
    }

    private void SetRowBackColor(GridViewRowEventArgs e, string color)
    {
        e.Row.BackColor = System.Drawing.Color.FromName(color);
        e.Row.Font.Bold = true;
        foreach (TableCell tc in e.Row.Cells)
        {
            if (IsInt(tc.Text))
                tc.Text = Convert.ToInt32(tc.Text).ToString("#,#");
        }
    }
    #endregion
}

Wednesday, October 12, 2011

AddressAccessDeniedException in WCF 2010

Today when executing the service it gives the below exception.
HTTP could not register
URL http://+:8002/.../. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for detail
s).
The reason for the above exception is given in the book Programming WCF Services O'REILLY by JUVAL LOWY
How to instruct windows to register the URL
  • Go to programs and select "Visual Studio Tools"
  • Right click on Visual Stutdio Command Prompt and select Run as administrator
We get a command prompt shows the path "C:\WINDOWS\system32" We have to give netsh http add urlacl url=http://+:8002/ user="MachineOrDomain\UserName"

Thursday, October 6, 2011

@@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT – Retrieve Last Inserted Identity of Record

@@IDENTITY SCOPE_IDENTITY IDENT_CURRENT IDENT_SEED IDENT_INCR
Any table
Current session
Any scopes.
Any table
Current session
Current scope.
Specific table
Any session
Any scope.
Returns the
original seed value
If we re-seed using
DBCC CHECKIDENT
won't change the
value.
Returns the
increment value
specified during
the creation of an
identity column in a
table or view
that has an identity
column.
Table or View Table or View Table or View
If user truncates or
drop the table
also, it
will return the last
identity value
generated in the
current session
If user truncates or
drop the table also,
it will return the last
identity value
generated in the
current session
If user truncated
the table it will
return the Ident_Seed
value.

It return null
when user drop
the table.
A scope is a module: a stored procedure, trigger, function, or batch.
Each query window in Query Analyzer is a session.

How to get all the session running in the server?
EXEC sp_who 'test';

How to check the current session
SELECT @@SPID       SessionID,
       USER_NAME()  AS [User_Name] ,
       SUSER_NAME() AS [Login identification name of the user.],
       CURRENT_USER AS [Name of the current user] ,
       SYSTEM_USER  AS [System_user],
       SESSION_USER AS [Session_user],
       USER         AS [User]

IDENT_SEED
  1. DBCC CHECKIDENT ('dbo.IdentityTest', RESEED, 10)
  2. Returns the original seed value, if we re-seed using DBCC CHECKIDENT.
  3. IDENT_SEED will return the seed value created for the Idetntiy column( when table creation or Alteration).
    It won't changed by DBCC CHECKIDENT ('dbo.IdentityTest', RESEED, 10)

References
RESED Identity Column
SQLAuthority

Monday, September 26, 2011

Trim Leading Or Trailing Control Characters

DECLARE @MyString VARCHAR(1000)
--Control character

DECLARE @Tab            VARCHAR(2)
DECLARE @LineFeed       VARCHAR(2)
DECLARE @CarriageReturn VARCHAR(2)
DECLARE @SearchPattern  VARCHAR(10)

SET @Tab            =              CHAR(9)
SET @LineFeed       =              CHAR(10)
SET @CarriageReturn =              CHAR(13)

--Search for any single of more chars not with specified range
SET @SearchPattern = '%[^ '   + @Tab + @LineFeed + @CarriageReturn + ']%'

SET @MyString = CHAR(10) + ' ' + CHAR(10)+ CHAR(9) + 'My name is ' + CHAR(10) 
				+ ' babu ' + CHAR(10) + ' ' + CHAR(10) + CHAR(10) + ' ' + CHAR(10)

SELECT LEN(@MyString) AS TotalLength
SELECT @MyString AS MyString

SELECT LEN( 
RTRIM( LTRIM( 
	SUBSTRING( @MyString, 
		PATINDEX(@SearchPattern, @MyString), 
		LEN(@MyString) - PATINDEX(@SearchPattern, @MyString) - PATINDEX(@SearchPattern, 
		REVERSE(@MyString)) + 2
		) 
	) ) 
) AS AfterTrimedLength

SELECT 
RTRIM( LTRIM( 
	SUBSTRING( @MyString, 
		PATINDEX(@SearchPattern, @MyString), 
		LEN(@MyString) - PATINDEX(@SearchPattern, @MyString) - PATINDEX(@SearchPattern, 
		REVERSE(@MyString)) + 2
		) 
	) ) AS AfterTrimed

Tuesday, September 13, 2011

Auto center pop up window

function PopupCenter() {
    var width = 600;
    var height = 480;
    var top = (screen.height / 2) - (height / 2);
    var left = (screen.width / 2) - (width / 2);

    var parametar = 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left;
    var url = 'Default.aspx'
    var windowName = 'Default';
    var targetWin = window.open(url, windowName, parametar);
    targetWin.focus();
    return false;
}
Page with query string
function PopupCenter(Name, Age) {
    var width = 600;
    var height = 480;
    var top = (screen.height / 2) - (height / 2);
    var left = (screen.width / 2) - (width / 2);

    var parametar = 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left;
    var url = 'Default.aspx?Name=' + Name + '&Age=' + Age;
    var windowName = 'Default';
    var targetWin = window.open(url, windowName, parametar);
    targetWin.focus();
    return false;
}
References
www.javascripter.net

msdn
htmlgoodies

Friday, August 5, 2011

Creating a Windows Service in C#.net and call a method every hour




Untitled Page





Untitled Page



In Visual Studio Select File->New->Project Select Windows and select Windows
Service


Right click on the Service1 designer and select Add Installer. This adds ProjectInstaller


Will create a file ProjectInstaller.cs





To avoid Set Service Login prompt being asked about the system username and
password you must change the Account for the serviceProcessInstaller to LocalSystem.

ServiceAccount Enumeration

ServiceAccount

stackoverflow





ServiceProcessInstaller Installs an executable containing classes that extend
ServiceBase. This class is called by installation utilities, such as InstallUtil.exe,
when installing a service application. ServiceInstaller Installs a class
that extends ServiceBase to implement a service. This class is called by the install
utility when installing a service application.



Display Name is show in name column of the service.
Set StartType as Automatic - To make the service to be started after restart/shutdown.

How to Start the service automatically after Installation?




Rename Service1 to to MyService


Create a folder and write the code to write to file


How to check whether the service called function is working or not? Right
click on the Solution(DemoService) and select Add -> New Project This console
application is used to test whether file writing works or not.


How to create Service Installer? Right click on the Solution(DemoService)
and select Add -> New Project Select Other Project Types -> Setup and Deployment
-> Setup Project


We will get the below screen.


Right click on the Setup project


Select the service project








Double click on the Application Folder


Press Ok.


Select the setup project and press F4 Manufacturer will come in path as "C:\Program
Files\ManufacturerValue" Title will come in Setup Wizard





Click on Configuration Manager


Change Debug mode to Release for the Service and Setup projects













To avoid this prompt give LocalSystem to Account property of serviceProcessInstaller.



Type control in run and select Administrative Tools -> Services







Make the service to call every 10 minutes Create a file as the below image


public class WriteToFile
    {
        public WriteToFile()
        {
            string strDateTime = DateTime.Now.ToString();
            StreamWriter sw = new StreamWriter(Path.Combine(System.IO.Path.GetTempPath(), "babu.txt"), true);
            sw.WriteLine(strDateTime);

            sw.Close();
        }
    }
Update the MyService.cs file
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using DemoService.Functions;
using System.Timers;

namespace DemoService
{
    public partial class MyService : ServiceBase
    {
        //Make the service to call the for every 5 min
        System.Timers.Timer TimerObj = new System.Timers.Timer(ConvertMinutesToMilliseconds(5));

        public MyService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            TimerObj.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            TimerObj.Enabled = true;
        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            TimerObj.Enabled = false;
        }

        /// 
        /// At the end of every 5 min the event will be triggered.
        /// 
        ///         /// protected void OnElapsedTime(object source, ElapsedEventArgs e)         {             //Write the current datetime to the file                          WriteToFile objWriteToFile = new WriteToFile();         }         ///          /// Convert minutes to milliseconds                 /// ///                  /// /// ///                  public static double ConvertMinutesToMilliseconds(double minutes)          {              return TimeSpan.FromMinutes(minutes).TotalMilliseconds;          }     } } 

Friday, July 8, 2011

Switch Theme Without Postback


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ChangeTheme : System.Web.UI.Page, ICallbackEventHandler
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        //If theme is null or not changed by user use Default theme
        if (String.IsNullOrEmpty(Convert.ToString(Session["Theme"])))
            Page.Theme = "Default";
        else
            Page.Theme = Convert.ToString(Session["Theme"]);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //JavaScript Callbacks
        ClientScriptManager scriptManager = Page.ClientScript;
        String cbReference = scriptManager.GetCallbackEventReference(this, "returnValue", "ReceiveServerData", "context");
        String callbackScript = "function CallServer(returnValue, context) {" + cbReference + "; }";
        scriptManager.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);

        TextBox1.Text = DateTime.Now.ToString();
    }

    #region ICallbackEventHandler Members
    //Return value from the server to the client
    string ICallbackEventHandler.GetCallbackResult()
    {
        return Convert.ToString(Session["Theme"]);
    }

    //Get the theme name from the javascript function
    public void RaiseCallbackEvent(string eventArgument)
    {
        Session["Theme"] = eventArgument.Trim();
    }

    #endregion
}

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ChangeTheme.aspx.cs" 
Inherits="ChangeTheme" %>




    Theme Switcher
    
    
    

    


    

The style set for the background body and the textbox.

You can see that, the time is not changed when we select the color.
This is done from the javascript.
To make apply the theme press the button Apply Theme.



Source Code

Saturday, March 26, 2011

GridView makeover using CSS

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

//http://atashbahar.com/post/GridView-makeover-using-CSS.aspx
public partial class StylishGridView_Demo_GridViewMakeOver : System.Web.UI.Page
{
    CustomersDataObject objData = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            objData = new CustomersDataObject();
            //DataTable dt =  objData.Select().Table ;
            gvStylish.DataSource = objData.Select();
            gvStylish.DataBind();
        }
    }

    protected void gvStylish_Sorting(object sender, GridViewSortEventArgs e)
    {
        //Change sort direction
        SortDirection = SortDirection == SortDirection.Descending ? SortDirection.Ascending : SortDirection.Descending;
        string sSortExpression = SortDirection == SortDirection.Ascending ? " Asc" : " Desc";

        //If new column, set as asc
        if (Convert.ToString(SortExpression) != e.SortExpression)
        {
            SortDirection = SortDirection.Ascending;
            sSortExpression = " Asc";
        }

        sSortExpression = e.SortExpression + sSortExpression;
        SortExpression = e.SortExpression;

        objData = new CustomersDataObject();
        gvStylish.DataSource = new DataView(objData.Select().Table, string.Empty, sSortExpression, DataViewRowState.CurrentRows);
        gvStylish.DataBind();
    }

    protected void gvStylish_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        objData = new CustomersDataObject();
        //DataTable dt =  objData.Select().Table ;
        gvStylish.PageIndex = e.NewPageIndex;
        gvStylish.DataSource = objData.Select();
        gvStylish.DataBind();
    }

    protected void gvStylish_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridView gridView = (GridView)sender;

        //You have to set the SortExpression in the aspx page.
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //To add tooltip for the header
            if (e.Row.RowType == DataControlRowType.Header)
            {
                foreach (TableCell cell in e.Row.Cells)
                {
                    foreach (Control ctl in cell.Controls)
                    {
                        if (ctl.GetType().ToString().Contains("DataControlLinkButton"))
                        {
                            cell.Attributes.Add("title", "Click to sort " + ((LinkButton)ctl).Text);
                        }
                    }
                }
            }

            //Set default header style for the gridview
            //Get sorted column index for the templated gridview
            SortIndex = -1;
            foreach (DataControlField field in gridView.Columns)
            {
                e.Row.Cells[gridView.Columns.IndexOf(field)].CssClass = "sortable";

                if (!string.IsNullOrEmpty(SortExpression))
                {
                    if (field.SortExpression == SortExpression)
                    {
                        SortIndex = gridView.Columns.IndexOf(field);
                    }
                }
            }

            //Set Sorted style for the gridview header
            if (SortIndex > -1)
                e.Row.Cells[SortIndex].CssClass = (SortDirection == SortDirection.Ascending
                                            ? " sortable sorted asc" : " sortable sorted desc");
        }
        else if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //To change color for the sorded gridvew entire column
            if (SortIndex > -1)
                e.Row.Cells[SortIndex].CssClass += (e.Row.RowIndex % 2 == 0 ? " sortaltrow" : "sortrow");

            //#region Add toolTip to the asp:CommandField Starts
            //int lastCell = e.Row.Cells.Count - 1;
            //foreach (Control ctrl in e.Row.Cells[lastCell].Controls)
            //{
            //    if (ctrl.GetType().BaseType.Name == "LinkButton")
            //    {
            //        LinkButton lnkBtn = ctrl as LinkButton;

            //        switch (lnkBtn.Text.Trim())
            //        {
            //            case "Edit":
            //                lnkBtn.ToolTip = "Click to edit the record.";
            //                break;

            //            case "Delete":
            //                lnkBtn.Attributes.Add("onclick", "javascript:return confirm('Do you want to delete the selected Course?');");
            //                lnkBtn.ToolTip = "Click to delete the record.";
            //                break;
            //        }
            //    }
            //}
            //#endregion
        }
    }

    #region "Properties"
    public Int32 SortIndex
    {
        get
        {
            if (ViewState["_SortIndex_"] == null)
                ViewState["_SortIndex_"] = -1;

            return (Int32)ViewState["_SortIndex_"];
        }
        set { ViewState["_SortIndex_"] = value; }
    }

    public string SortExpression
    {
        get
        {
            if (ViewState["_SortExpression_"] == null)
                ViewState["_SortExpression_"] = string.Empty;

            return (string)ViewState["_SortExpression_"];
        }
        set { ViewState["_SortExpression_"] = value; }
    }

    public SortDirection SortDirection
    {
        get
        {
            if (ViewState["_SortDirection_"] == null)
                ViewState["_SortDirection_"] = SortDirection.Ascending;

            return (SortDirection)ViewState["_SortDirection_"];
        }
        set { ViewState["_SortDirection_"] = value; }
    }

    #endregion
}

#container /*make horizontal center of a div*/
{
 margin: 10px auto;
 width: 700px;
}
.mGrid
{
 background-color: #fff;
 border: solid 1px #525252;
 border-collapse: collapse;
 margin: 5px 0 10px 0;
 width: 100%;
 font: 11px Tahoma;
}

/*Header style starts*/
.mGrid tr th
{
 background: #424242 url(Images/grd_head.png) repeat-x top;
 border:0px;
 border-bottom: 1px solid #c1c1c1;
 border-right: 1px solid #c1c1c1;
 color: #fff;
 font-size: 0.9em;
 padding: 4px 2px;
}

/*Sorting Starts*/
.mGrid tr th.sortable
{
 padding: 0px;
}

.mGrid tr th.sortable:hover
{
 background: #b7e7fb url('Images/grid-header-sortable-back-hover.gif') top left repeat-x;
 border: 1px solid #C4C4C4;
 border-left: none;
 border-top: none;
}

.mGrid tr th.sortable a
{
 color: white;
 display: block;
 min-height: 1px;
 padding: 3px 3px 2px 2px;
 text-decoration: none;
}

.mGrid tr th.sortable a:hover
{
 text-decoration: none;
}

.mGrid tr th.sorted
{
 background: #d8ecf6 url('Images/grid-header-sorted-back.jpg') top left repeat-x;
 border: 1px solid #8B8878;
 border-left: none;
 border-top: none;
}

.mGrid tr th.asc a
{
 background: transparent url('Images/grid-header-asc-glyph.gif') center 1px no-repeat;
}

.mGrid tr th.desc a
{
 background: transparent url('Images/grid-header-desc-glyph.gif') center 1px no-repeat;
}
/*Sorting Ends*/

.mGrid tr .RowStyle
{
 border: 1px solid red;
 padding: 2px 6px 2px 4px;
}

.mGrid tr.alt
{
 background: #f2f9fc;
}

.mGrid tr.RowStyle:hover, .mGrid tr.alt:hover
{
 background: #c1c1c1 url(Images/grid-header-hover.gif) repeat-x top;
}


/*Select entire sorted column starts*/
.mGrid tr.RowStyle .sortaltrow, .mGrid tr.alt .sortaltrow 
{
    background-color: #D6D6D6;
}

.mGrid tr.RowStyle .sortrow, .mGrid tr.alt .sortrow 
{
    background-color: #EAEAEA;
}
/*Select entire sorted column ends*/

.mGrid .pgr
{
 background: #424242 url(Images/grd_pgr.png) repeat-x top;
 text-align: center; /*Make pager to be center*/
}
.mGrid .pgr table
{
 margin: 5px 0;
}
.mGrid .pgr td
{
 border-width: 0;
 color: #fff;
 font-weight: bold;
 line-height: 12px;
 padding: 0 6px;
 border-left: solid 1px #666;
}
.mGrid .pgr a
{
 color: #666;
 text-decoration: none;
}
.mGrid .pgr a:hover
{
 color: #000;
 text-decoration: none;
}



Download Images
Curtesy atashbahar

Monday, February 28, 2011

Grouping RadioButton inside gridveiw

        function uncheckOthers(id) {
            var elm = document.getElementsByTagName('input');
            for (var i = 0; i < elm.length; i++) {
                if (elm.item(i).id.substring(id.id.lastIndexOf('_')) == id.id.substring(id.id.lastIndexOf('_'))) {
                    if (elm.item(i).type == "radio" && elm.item(i) != id) elm.item(i).checked = false;
                }
            }
        }  
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //To make the RadioButton mutually exclusive
                string strScript = "uncheckOthers(" + ((RadioButton)e.Row.Cells[0].FindControl("rbSelect")).ClientID + ");";
                ((RadioButton)e.Row.Cells[0].FindControl("rbSelect")).Attributes.Add("onclick", strScript);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Selecting or DeSelecting multiple checkbox inside a gridview




function SelectAllOrDeselect(CheckBox, Type, Column, HCheckBox) {
    try {
        var TotalChkBx = parseInt('<%= grd_EmpSelection.Rows.Count %>');
        var TargetBaseControl = document.getElementById('<%= grd_EmpSelection.ClientID%>');
        var TargetChildControl = null;

        if (Column == "1") TargetChildControl = "chkTestSelect";
        else TargetChildControl = "chkTrainingSelect";

        var Inputs = TargetBaseControl.getElementsByTagName("input");
        var SelectCount = 0;
        //Checked/Unchecked all the checkBoxes in side the GridView.
        if (Type == "1") {
            for (var iCount = 0; iCount < Inputs.length; ++iCount) {
                if (Inputs[iCount].type == 'checkbox' && Inputs[iCount].id.indexOf(TargetChildControl, 0) >= 0) 
                    Inputs[iCount].checked = CheckBox.checked;
            }

            //Reset Counter
            SelectCount = CheckBox.checked ? TotalChkBx : 0;
        } else if (Type == "2") {
            //Reset Counter
            for (var iCount = 0; iCount < Inputs.length; ++iCount) {
                if (Inputs[iCount].type == 'checkbox' && Inputs[iCount].id.indexOf(TargetChildControl, 0) >= 0) 
                    if (Inputs[iCount].checked == true) SelectCount++;
            }

            //Modifiy Counter;        
            if (!CheckBox.checked && SelectCount > 0) SelectCount--;

            //Change state of the header CheckBox.
            if (SelectCount < TotalChkBx) HCheckBox.checked = false;
            else if (SelectCount == TotalChkBx) HCheckBox.checked = true;
        }
    } catch (err) {}
}
protected void grd_EmpSelection_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //e.Row.RowState == DataControlRowState.Edit not works on Alternating Rows 
        //if ((e.Row.RowState & DataControlRowState.Edit) > 0)
        if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
        {

            CheckBox chkTestSelectAll = (CheckBox)this.grd_EmpSelection.HeaderRow.FindControl("chkTestSelectAll");
            CheckBox chkTestSelect = (CheckBox)e.Row.Cells[1].FindControl("chkTestSelect");

            chkTestSelectAll.Attributes["onclick"] = string.Format("javascript:SelectAllOrDeselect(this,'1','1', {0});", chkTestSelectAll.ClientID);
            chkTestSelect.Attributes["onclick"] = string.Format("javascript:SelectAllOrDeselect(this,'2','1', {0});", chkTestSelectAll.ClientID);


            CheckBox chkTrainingSelectAll = (CheckBox)this.grd_EmpSelection.HeaderRow.FindControl("chkTrainingSelectAll");
            CheckBox chkTrainingSelect = (CheckBox)e.Row.Cells[1].FindControl("chkTrainingSelect");

            chkTrainingSelectAll.Attributes["onclick"] = string.Format("javascript:SelectAllOrDeselect(this,'1','2', {0});", chkTrainingSelectAll.ClientID);
            chkTrainingSelect.Attributes["onclick"] = string.Format("javascript:SelectAllOrDeselect(this,'2','2', {0});", chkTrainingSelectAll.ClientID);

        }
    }

The gridview checkbox will maintain the checked state during postback.

Reference
http://www.codeproject.com/KB/webforms/SelectingAllCheckBoxes.aspx