Today i'm going to show you how to select all records in a gridview from one
checkbox which located in gridview header.
First set gridview like below code snnippet
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound"
>
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="allchk"
runat="server" Text="All" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="selectchk"
runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TR. ID">
<ItemTemplate>
<asp:Label ID="namelbl"
runat="server" Text='<%#Eval(
"name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In the next step you have to write small java script code.
<script type="text/javascript">
function SelectAll(id)
{
var grid = document.getElementById("<%= GridView1.ClientID %>");
var cell;
if (grid.rows.length > 0)
{
for (i=1; i<grid.rows.length; i++)
{
cell = grid.rows[i].cells[0];
for (j=0; j<cell.childNodes.length; j++)
{
if (cell.childNodes[j].type =="checkbox")
{
cell.childNodes[j].checked = document.getElementById(id).checked;
}
}
}
}
}
</script>
Next, in gridview rowdatabound event add javascript function to the all select checkbox onclick event.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)<br />
{
if (e.Row.RowType == DataControlRowType.Header)
{
((CheckBox)e.Row.FindControl("allchk")).Attributes.Add("onclick",
"javascript:SelectAll('" +
((CheckBox)e.Row.FindControl("allchk")).ClientID + "')");
}
}
Happy programming!
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.
The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.