Search This Blog

Monday, August 30, 2010

Deleting Multiple Rows in a GridView

If you have used Hotmail or any other similar email client, you might have observed that  we have the option of selecting multiple rows (using the checkbox provided) and perform a set of operations on them. In this article, we will replicate this scenario for a gridview. A gridview allows us to delete only a single row at a time. We will extend this functionality to select multiple rows and delete all of the selected rows in a single stroke. In this article, I assume that you are aware of creating asp.net web applications and have worked with gridview.
The sample makes use of the Northwind database. We will be pulling data from the Employee table. For this sample to work, drop all the Foreign Key relationships on the Employee Table. To do so, in Sql Server Management Studio, browse to the Northwind database and open the Employee table in design view. Right click in the Table designer on the right hand side and choose ‘Relationships’. Select all the relationships like FK_Orders_Employees,  FK_EmployeeTerritories_Employees etc and delete them. This step is necessary as we will get a constraint violation exception if we do not do so.
Once we are through with the task of removing the relationships in the Employee table, let us explore the steps to create a gridview with functionality to delete multiple rows at a time.
Perform the following steps :
Step 1: Create an .aspx page and add a GridView and a SqlDataSource control to it.
Step 2: Configure the connection of SqlDataSource to point to the Northwind database.  Create queries for the Select and Delete commands. The resultant code will look similar as given below :
<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
    SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
    DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
       <DeleteParameters>
           <asp:Parameter Name="EmployeeID" />
       DeleteParameters>
asp:SqlDataSource>                                   
Step 3: Once the SqlDataSource has been configured, bind the gridview with this data source.
Step 4: To create a checkbox in each row, follow these steps:
1.    Create a TemplateField inside the <Columns> to add custom content to each column.
2.    Inside the TemplateField, create an ItemTemplate with a CheckBox added to it.
<asp:TemplateField>
       <ItemTemplate>
             <asp:CheckBox ID="chkRows" runat="server"/>
      ItemTemplate>
 asp:TemplateField>
This will add a checkbox to each row in the grid.
Step 5: Add a button control, and rename it to btnMultipleRowDelete.
The resultant markup in the design view will look similar to the code below :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1">
  
   <Columns>
      <asp:TemplateField>
          <ItemTemplate>
            <asp:CheckBox ID="cbRows" runat="server"/>
          ItemTemplate>
       asp:TemplateField>
 
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
   Columns>
asp:GridView>
 
<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
   <DeleteParameters>
       <asp:Parameter Name="EmployeeID" />
   DeleteParameters>
asp:SqlDataSource>
 
<asp:Button
   ID="btnMultipleRowDelete"
   OnClick="btnMultipleRowDelete_Click"
   runat="server"
   Text="Delete Rows" />
 
In Code behind file (.cs) for C# and (.vb) for VB.NET, code the button click event. Our code will first loop through all the rows in the GridView. If a row is checked, the code retrieves the EmployeeID and passes the selected value to the Delete Command.
C#
 
 
protected void btnMultipleRowDelete_Click(object sender, EventArgs e)
{
        // Looping through all the rows in the GridView
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox checkbox = (CheckBox)row.FindControl("cbRows");
 
            //Check if the checkbox is checked.
//value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter.
            if (checkbox.Checked)
            {
                // Retreive the Employee ID
int employeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
// Pass the value of the selected Employye ID to the Delete //command.
SqlDataSource1.DeleteParameters["EmployeeID"].DefaultValue = employeeID.ToString();
                SqlDataSource1.Delete();
            }
        }
 }

Saturday, August 28, 2010

How to show Print Dialog Box when a button is clicked(Window Application)

 private void button1_Click(object sender, EventArgs e)
{
        PrintDialog p = new PrintDialog(); 
                 p.ShowDialog();

}

Friday, August 27, 2010

Abstract Class versus Interface

Introduction

In this article along with the demo project I will discuss Interfaces versus Abstract classes. The concept of Abstract classes and Interfaces is a bit confusing for beginners of Object Oriented programming. Therefore, I am trying to discuss the theoretical aspects of both the concepts and compare their usage. And finally I will demonstrate how to use them with C#.

Background

An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let's explain both concepts and compare their similarities and differences.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn�t support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:
Feature Interface Abstract class
Multiple inheritance A class may inherit several interfaces. A class may inherit only one abstract class.
Default implementation An interface cannot provide any code, just the signature. An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface. An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity If various implementations only share method signatures then it is better to use Interfaces. If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed Requires more time to find the actual method in the corresponding classes. Fast
Adding functionality (Versioning) If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined

Using the Code

Let me explain the code to make it a bit easier. There is an Employee abstract class and an IEmployee interface. Within the Abstract class and the Interface entity I am commenting on the differences between the artifacts.
I am testing both the Abstract class and the Interface by implementing objects from them. From the Employee abstract class, we have inherited one object: Emp_Fulltime. Similarly from IEmployee we have inherited one object: Emp_Fulltime2.
In the test code under the GUI, I am creating instances of both Emp_Fulltime and Emp_Fulltime2 and then setting their attributes and finally calling the calculateWage method of the objects.

Abstract Class Employee

Collapse
using System;

namespace AbstractsANDInterfaces
{
    /// 


    /// Summary description for Employee.

    /// 

    
    public abstract class Employee
    {
        //we can have fields and properties 


        //in the Abstract class

        protected String id;
        protected String lname;
        protected String fname;

        //properties


        public abstract String ID
        {
            get;
            set;
        }

        public abstract String FirstName
        {
            get;
            set;
        }
        
        public abstract String LastName
        {
            get;
            set;
        }
        //completed methods


        public String Update()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " updated";
        }
        //completed methods


        public String Add()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " added";
        }
        //completed methods


        public String Delete()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " deleted";
        }
        //completed methods


        public String Search()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " found";
        }

        //abstract method that is different 


        //from Fulltime and Contractor

        //therefore i keep it uncompleted and 

        //let each implementation 

        //complete it the way they calculate the wage.


        public abstract String CalculateWage();
        
    }
}

Interface Employee

Collapse
using System;


namespace AbstractsANDInterfaces
{
    /// <summary>


    /// Summary description for IEmployee.

    /// </summary>

    public interface IEmployee
    {
        //cannot have fields. uncommenting 


        //will raise error!
        //        protected String id;
        //        protected String lname;
        //        protected String fname;


        //just signature of the properties 

        //and methods.

        //setting a rule or contract to be 

        //followed by implementations.


        String ID
        {
            get;
            set;
        }

        String FirstName
        {
            get;
            set;
        }
        
        String LastName
        {
            get;
            set;
        }
        
        // cannot have implementation


        // cannot have modifiers public 

        // etc all are assumed public

        // cannot have virtual


        String Update();

        String Add();

        String Delete();

        String Search();

        String CalculateWage();
    }
}

Inherited Objects

Emp_Fulltime:
Collapse
using System;

namespace AbstractsANDInterfaces
{
    /// 


    /// Summary description for Emp_Fulltime.

    /// 

     
    //Inheriting from the Abstract class

    public class Emp_Fulltime : Employee
    {
        //uses all the properties of the 


        //Abstract class therefore no 

        //properties or fields here!


        public Emp_Fulltime()
        {
        }


        public override String ID
        {
            get

            {
                return id;
            }
            set
            {
                id = value;
            }
        }
        
        public override String FirstName
        {
            get

            {
                return fname;
            }
            set
            {
                fname = value;
            }
        }

        public override String LastName
        {
            get

            {
                return lname;
            }
            set
            {
                lname = value;
            }
        }

        //common methods that are 

        //implemented in the abstract class

        public new String Add()
        {
            return base.Add();
        }
        //common methods that are implemented 


        //in the abstract class

        public new String Delete()
        {
            return base.Delete();
        }
        //common methods that are implemented 


        //in the abstract class

        public new String Search()
        {
            return base.Search();
        }
        //common methods that are implemented 


        //in the abstract class

        public new String Update()
        {
            return base.Update();
        }
        
        //abstract method that is different 


        //from Fulltime and Contractor

        //therefore I override it here.

        public override String CalculateWage()
        {
            return "Full time employee " + 
                  base.fname + " is calculated " + 
                  "using the Abstract class...";
        }
    }
}
Emp_Fulltime2:
Collapse
using System;

namespace AbstractsANDInterfaces
{
    /// 

    /// Summary description for Emp_fulltime2.


    /// 

    
    //Implementing the interface

    public class Emp_fulltime2 : IEmployee
    {
        //All the properties and 


        //fields are defined here!

        protected String id;
        protected String lname;
        protected String fname;

        public Emp_fulltime2()
        {
            //


            // TODO: Add constructor logic here

            //

        }

        public String ID
        {
            get

            {
                return id;
            }
            set
            {
                id = value;
            }
        }
        
        public String FirstName
        {
            get
            {
                return fname;
            }
            set

            {
                fname = value;
            }
        }

        public String LastName
        {
            get
            {
                return lname;
            }
            set
            {
                lname = value;
            }
        }

        //all the manipulations including Add,Delete, 


        //Search, Update, Calculate are done

        //within the object as there are not 

        //implementation in the Interface entity.

        public String Add()
        {
            return "Fulltime Employee " + 
                          fname + " added.";
        }

        public String Delete()
        {
            return "Fulltime Employee " + 
                        fname + " deleted.";
        }

        public String Search()
        {
            return "Fulltime Employee " + 
                       fname + " searched.";
        }

        public String Update()
        {
            return "Fulltime Employee " + 
                        fname + " updated.";
        }
        
        //if you change to Calculatewage(). 


        //Just small 'w' it will raise 

        //error as in interface

        //it is CalculateWage() with capital 'W'.

        public String CalculateWage()
        {
            return "Full time employee " + 
                  fname + " caluculated using " + 
                  "Interface.";
        }
    }
}

Code for Testing

Collapse
//This is the sub that tests both 

//implementations using Interface and Abstract

private void InterfaceExample_Click(object sender, 
                                System.EventArgs e)
{
    try

    {

        IEmployee emp;

        Emp_fulltime2 emp1 = new Emp_fulltime2();

        emp =  emp1;
        emp.ID = "2234";
        emp.FirstName= "Rahman" ;
        emp.LastName = "Mahmoodi" ;
        //call add method od the object


        MessageBox.Show(emp.Add().ToString());
        
        //call the CalculateWage method

        MessageBox.Show(emp.CalculateWage().ToString());


    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

}

private void cmdAbstractExample_Click(object sender, 
                                   System.EventArgs e)
{

    Employee emp;

    emp = new Emp_Fulltime();
    

    emp.ID = "2244";
    emp.FirstName= "Maria" ;
    emp.LastName = "Robinlius" ;
    MessageBox.Show(emp.Add().ToString());

    //call the CalculateWage method


    MessageBox.Show(emp.CalculateWage().ToString());

}
 
 
Recommendations on using Abstract Classes and Interfaces
1. If you anticipate creating multiple versions of your component, create an
abstract class. Abstract classes provide a simple and easy way to
version your components. By updating the base class, all inheriting
classes are automatically updated with the change. Interfaces, on the
other hand, cannot be changed once created. If a new version of an
interface is required, you must create a whole new interface. 
 
2. If the functionality you are creating will be useful across a wide
range of disparate objects, use an interface. Abstract classes should
be used primarily for objects that are closely related, whereas
interfaces are best suited for providing common functionality to
unrelated classes. 
 
3. If you are designing small, concise bits of functionality, use interfaces.
If you are designing large functionalunits, use an abstract class. 
 
4. If you want to provide common,implemented functionality among all
implementations of your component,use an abstract class. 
Abstract classes allow you to partially implement your class,
whereas interfaces contain no implementation for any members. 

Understanding Delegates in C#

Introduction

Delegate is like a buzz word in C#.NET programming. In this article, I explain delegates, multicast delegates and their usage with the help of simple C# programs.

What is a Delegate?

Delegate is a type which  holds the method(s) reference in an object. It is also referred to as a type safe function pointer.

Advantages

  • Encapsulating the method's call from caller
  • Effective use of delegate improves the performance of application
  • Used to call a method asynchronously

Declaration


public delegate type_of_delegate delegate_name()
Example:

public delegate int mydelegate(int delvar1,int delvar2)

Note

  • You can use delegates without parameters or with parameter list
  • You should follow the same syntax as in the method
    (If you are referring to the method with two int parameters and int return type, the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer.)

Sample Program using Delegate


public delegate double Delegate_Prod(int a,int b);
class Class1
{
    static double fn_Prodvalues(int val1,int val2)
    {
        return val1*val2;
    }
    static void Main(string[] args)
    {
        //Creating the Delegate Instance
        Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
        Console.Write("Please Enter Values");
        int v1 = Int32.Parse(Console.ReadLine());
        int v2 = Int32.Parse(Console.ReadLine());
        //use a delegate for processing
        double res = delObj(v1,v2);
        Console.WriteLine ("Result :"+res);
        Console.ReadLine();
    }
}

Explanation

Here I have used a small program which demonstrates the use of delegate.
The delegate "Delegate_Prod" is declared with double return type and accepts only two integer parameters.
Inside the class, the method named fn_Prodvalues is defined with double return type and two integer parameters. (The delegate and method have the same signature and parameter type.)
Inside the Main method, the delegate instance is created and the function name is passed to the delegate instance as follows:

Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
After this, we are accepting the two values from the user and passing those values to the delegate as we do using method:

delObj(v1,v2);
Here delegate object encapsulates the method functionalities and returns the result as we specified in the method.

Multicast Delegate

What is Multicast Delegate?

It is a delegate which holds the reference of more than one method.
Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate


delegate void Delegate_Multicast(int x, int y);
Class Class2
{
    static void Method1(int x, int y)
    {
        Console.WriteLine("You r in Method 1");
    }

    static void Method2(int x, int y)
    {
        Console.WriteLine("You r in Method 2");
    }

    public static void "on" />Main()
    {
        Delegate_Multicast func = new Delegate_Multicast(Method1);
        func += new Delegate_Multicast(Method2);
        func(1,2);             // Method1 and Method2 are called
        func -= new Delegate_Multicast(Method1);
        func(2,3);             // Only Method2 is called
    }
}

Explanation

In the above example, you can see that two methods are defined named method1 and method2 which take two integer parameters and return type as void.
In the main method, the Delegate object is created using the following statement:

Delegate_Multicast func = new Delegate_Multicast(Method1);
Then the Delegate is added using the += operator and removed using the -= operator.

Boxing and UnBoxing in C#

Introduction

In this article I will explain the concepts of Boxing and UnBoxing. C# provides us with Value types and Reference Types. Value Types are stored on the stack and Reference types are stored on the heap. The conversion of value type to reference type is known as boxing and converting reference type back to the value type is known as unboxing.
Let me explain you little more about Value and Reference Types.

Value Types

Value types are primitive types that are mapped directly to the FCL. Like Int32 maps to System.Int32, double maps to System.double. All value types are stored on stack and all the value types are derived from System.ValueType. All structures and enumerated types that are derived from System.ValueType are created on stack, hence known as ValueType.

Reference Types

Reference Types are different from value types in such a way that memory is allocated to them from the heap. All the classes are of reference type. C# new operator returns the memory address of the object.

Examples

Lets see some examples to have a better understanding of Value Types and Reference Types. Since we know that all ValueTypes are derived from System.Value we can write something like this:

System.ValueType r = 5;       
So what do you think about the above line of code. Will it compile ? Yes it will compile. But wait what type is it cause I don't remember any type which is called System.ValueType since its a base class from which all value types inherit. So is it Int32, Int64,double, decimal etc. It turns out that the type for variable 'r' is System.Int32. The Question arrises why Int32 and why not Int16. Well its because it is mapped to Int32 by default depending upon the Initial value of the variable.
You cannot write something like this since System.ValueType is not a primitive type its a base class for primitive value types and these mathematical operations can be performed on primitive types.

System.ValueType r = 10; 
r++;
In the above example I told you that variable 'r' will be a System.Int32 variable but if you don't believe me than you can find out yourself using the GetType() method:

System.ValueType r = 5;
 Console.WriteLine(r.GetType()) // returns System.Int32; 
Here are few samples you can try on your own:

        System.ValueType r = 23.45; 
        Console.WriteLine(r.GetType()); // what does this print
        //-------------------------------------------------------
        System.ValueType r = 23.45F; 
        Console.WriteLine(r.GetType()); // What does this print
        //-------------------------------------------------------
        System.ValueType r = 2U; 
        Console.WriteLine(r.GetType()); // What does this print
        //-------------------------------------------------------
        System.ValueType r = 'c';
        Console.WriteLine(r.GetType()); // What does this print
        //-------------------------------------------------------
        System.ValueType r = 'ac';
        Console.WriteLine(r.GetType()); // tricky 
        //-------------------------------------------------------
        System.ValueType r = "Hello World"; 
        Console.WriteLine(r.GetType()); // tricky
        
        
Lets now jump to Boxing. Sometimes we need to convert ValueTypes to Reference Types also known as boxing. Lets see a small example below. You see in the example I wrote "implicit boxing" which means you don't need to tell the compiler that you are boxing Int32 to object because it takes care of this itself although you can always make explicit boxing as seen below right after implicit boxing.

Int32 x = 10; 
        object o = x ;  // Implicit boxing
        Console.WriteLine("The Object o = {0}",o); // prints out 10
        //-----------------------------------------------------------
        Int32 x = 10; 
        object o = (object) x; // Explicit Boxing
        Console.WriteLine("The object o = {0}",o); // prints out 10
        
        
Lets now see UnBoxing an object type back to value type. Here is a simple code that unbox an object back to Int32 variable. First we need to box it so that we can unbox.

Int32 x = 5; 
        object o = x; // Implicit Boxing
        x = o; // Implicit UnBoxing
        
So, you see how easy it is to box and how easy it is to unbox. The above example first boxs Int32 variable to an object type and than simply unbox it to x again. All the conversions are taking place implicitly. Everything seems right in this example there is just one small problem which is that the above code is will not compile. You cannot Implicitly convert a reference type to a value type. You must explicity specify that you are unboxing as shown in the code below.

Int32 x = 5; 
        object o = x; // Implicit Boxing
        x = (Int32)o; // Explicit UnBoxing
        
Lets see another small example of unboxing.

Int32 x = 5; // declaring Int32
        Int64 y = 0; // declaring Int64 double
        object o = x; // Implicit Boxing
        y = (Int64)o; // Explicit boxing to double
        Console.WriteLine("y={0}",y); 
        
This example will not work. It will compile successfully but at runtime It will generate an exception of System.InvalidCastException. The reason is variable x is boxed as Int32 variable so it must be unboxed to Int32 variable. So, the type the variable uses to box will remain the same when unboxing the same variable. Of course you can cast it to Int64 after unboxing it as Int32 as follows:

Int32 x = 5; // declaring Int32
        Int64 y = 0; // declaring Int64 double
        object o = x; // Implicit Boxing
        y = (Int64)(Int32)o; // Unboxing and than casting to double
        Console.WriteLine("y={0}",y); 
        
I am sure that you all have grasp the basic understanding of Boxing and Unboxing. Happy Coding and practise a lot !

Thursday, August 26, 2010

Sql Query To remove Duplicate Records From Table?

Question: How to remove duplicate records from a table using SQL?

Answer: There may be quite a few possible ways of doing this, but the two most common ways are:-

Simpler and Faster approach - In this approach we simply create anothet table having only the distinct rows of the original table, drop the original table, and finally rename the new table to the original table. Voila! We're done. But, do remember that dropping a table will drop all the indexes and priviledges as well. So, you'll need to create them again.

CREATE TABLE NEW_TABLE AS SELECT DISTINCT * FROM ORIGINAL_TABLE;
DROP TABLE ORIGINAL_TABLE;
RENAME NEW_TABLE TO ORIGINAL_TABLE;
...create indexes/privileges on ORIGINAL_TABLE now...

The standard ROWID approach - it's the same approach where we simply compare the ROWID of the records having the same key values (duplicate records) and select only one of the duplicate rows - the one having either the min or the max ROWID. Don't worry, these ROWIDs are system generated and will never be duplicate, so you won't be having more than one min (or max).

DELETE FROM ORIGINAL_TABLE T1 WHERE ROWID > (SELECT MIN(ROWID) FROM ORIGINAL_TABLE T2WHERE T1.KEY = T2.KEY);
OR
DELETE FROM ORIGINAL_TABLE T1 WHERE ROWID < (SELECT MAX(ROWID) FROM ORIGINAL_TABLE T2WHERE T1.KEY = T2.KEY);

Here KEY represents the set of columns based on which we're deciding the duplicates.

Thursday, August 5, 2010

How to add radiobuttons in gridview and return row datakey value on their click

Source code of gridview is given below. In this i have used literal control in place of radiobutton. At runtime i will convert literal control in to radio control

   1:  <asp:GridView ID="GridDisc" runat="server" AutoGenerateColumns="False" AllowSorting="true" 
   2:           DataKeyNames="AdminDisciplineID" onrowdatabound="GridDisc_RowDataBound" 
   3:          onrowcreated="GridDisc_RowCreated" Width="1000px">              
   4:  <Columns>
   5:   
   6:  <asp:TemplateField >
   7:         <ItemTemplate >
   8:                 <asp:Literal ID="RadioButtonMarkup" runat="server">asp:Literal>
   9:         ItemTemplate>
  10:  asp:TemplateField>
  11:  <asp:TemplateField  HeaderText="AdminDisciplineCode" >
  12:  <ItemTemplate>
  13:  <asp:HyperLink ID="AdminDisciplineID" runat="server" Text='<%# Eval("AdminDisciplineCode") %>' />
  14:  ItemTemplate>
  15:  asp:TemplateField>
  16:     <asp:BoundField ItemStyle-CssClass="top"  HeaderText="Discipline Name" DataField="DisciplineName"/>
  17:     <asp:BoundField ItemStyle-CssClass="top"  HeaderText="DisciplineDescription" DataField="DisciplineDescription" />
  18:     <asp:BoundField  ItemStyle-CssClass="top" HeaderText="Active" DataField="Active"/>
  19:    <asp:BoundField  ItemStyle-CssClass="top" HeaderText="ModifiedOn" DataField="ModifiedOn"/>
  20:  Columns>                
  21:  asp:GridView>
 
Below is c# code to generate radio button at run time and
 i  have used property to return datakeyvalue of row on radiobutton click
 




   1:  protected void GridDisc_RowCreated(object sender, GridViewRowEventArgs e
   2:      {
   3:          if (e.Row.RowType == DataControlRowType.DataRow && 
   4:               (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
   5:          {
   6:             
   7:         Literal output = (Literal)e.Row.FindControl("RadioButtonMarkup");
   8:         output.Text = string.Format(@"< input type equalto 'radio' name='SuppliersGroup' "
              @"id='RowSelector{0}' value='{0}' />",e.Row.RowIndex);
                  // replace equal to by =  in just above line written
   9:          }
  10:      }
  11:  
  12:   
  13:  private int SuppliersSelectedIndex
  14:      {
  15:          get
  16:          {
  17:              if (string.IsNullOrEmpty(Request.Form["SuppliersGroup"]))
  18:                  return -1;
  19:              else                               
  20:             return Convert.ToInt32(Request.Form["SuppliersGroup"]);
  21:          }
  22:      }
  23:   
  24:   protected void link_Click1(object sender, EventArgs e)
  25:   {
  26:   
  27:  a = Convert.ToString(GridDisc.DataKeys[SuppliersSelectedIndex].Value); 
  28:             //calling property to get datakey value retuned
  29:  }
Here SuppliersSelectedIndex is property Below screenshot of gridview is given
Gridview screen shot