Datagridview With CheckBox

/* To Create a DatagridView with checkbox */

<asp:TemplateField HeaderText=”Select”>

<HeaderTemplate>

<asp:CheckBox runat=”server” Text=”All”">All(this);” />

</HeaderTemplate>

<ItemTemplate>

<asp:CheckBoxchkSelect” runat=”server” />

</ItemTemplate>

</asp:TemplateField>

/* Javascript function  to select all check boxes */

<script language=”javascript” type=”text/javascript”>

function All(CheckBox)

{

TotalChkBx = parseInt(‘<%= this.GridView1.Rows.Count %>’);

var TargetBaseControl = document.getElementById(‘<%= this.GridView2.ClientID %>’);

var TargetChildControl = “chkSelect“;

var Inputs = TargetBaseControl.getElementsByTagName(“input”);

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;

}

}

</script>

In code Behind

/* To get which are the values are selected in checkbox */

protected void btnsub_Click(object sender, EventArgs e)

{

CheckBox cbk = new CheckBox();

GridViewRowCollection gv = GridView1.Rows;

//foreach (GridViewRowCollection gv in GridView1.Rows)

foreach (GridViewRow gr in gv)

{

cbk = (CheckBox)(gr.Cells[0].FindControl(“chkSelect”));

if (cbk.Checked == true)

{

//  Which is the value required from the Datagrid View gr.Cells[2].Text.Trim();

Response.Write(gr.Cells[2].Text);

System.Threading.Thread.Sleep(100);

}

}

}