18/10/2014 by Nitesh

How To Add A CheckBox Column to GridView in ASP.Net

Friends,

Many a times, we need to give users a Checkbox in a GridView that users can use to select multiple rows from the GridView. In one of my previous post, we saw how we can do this in Windows Forms. In this post, we will see how can we add a CheckBox column to an existing GridView control in ASP.Net.

Let’s get started. We assume that we have a GridView with existing set of columns getting populated with some data. So, we have the below definition of GridView in our ASPX page.


            
            
                
                
            
            
            
            
            
            
            
            
            
            
            
        

And we have the below code to populate the GridView with some dummy data.

        private void LoadGridData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Id");
            dt.Columns.Add("Name");

            for (int i = 0; i < 10; i++)
            {
                DataRow dr = dt.NewRow();
                dr["Id"] = i + 1;
                dr["Name"] = "Student " + (i + 1);

                dt.Rows.Add(dr);
            }
            grdData.DataSource = dt;
            grdData.DataBind();
        }

The output of the above code is something like below.

gridview-checkbox-1

Now, we will be adding a CheckBox column to this Grid. For doing this, we will make use of TemplateField and define a new TemplateField column in the existing set of columns as below -

    
        
            
        
    

Your final GridView definition will appear like below –


            
            
                
                    
                        
                    
                
                
                
            
            
            
            
            
            
            
            
            
            
            
        

Save the code and refresh your ASPX page. Now, you will see a CheckBox appearing beside each row in your GridView.

gridview-checkbox-2

Hope you like this! Keep learning and sharing! Cheers!

#.Net#ASP.Net#GridView