First Add Check Box column in Gridview as Follows
<asp:GridView runat="server" ID="grv" AutoGenerateColumns="false" GridLines="Vertical"
BorderWidth="0" AllowPaging="true" PagerStyle-HorizontalAlign="Center" OnRowCreated="grvClassCaption_RowCreated">
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Center" HeaderText="Select All" ItemStyle-HorizontalAlign="Center"
HeaderStyle-CssClass="GridHeader" ItemStyle-Width="200px">
<HeaderTemplate>
<asp:CheckBox ID="chkHeader" runat="server" Text="Select All" Onclick="SetCheckBoxes(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkBox" runat="server" Text="Select" Onclick="ChangeHeader()" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Center" HeaderText="Name" ItemStyle-HorizontalAlign="Center"
HeaderStyle-CssClass="GridHeader" ItemStyle-VerticalAlign="Top" ItemStyle-CssClass="GridColumn"
ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div>
<asp:Button ID="Button1" runat="server" Text="SAVE" OnClick="BtnSave_Click" />
</div>
And ADD Following Script to the header of page
<script type="text/javascript">
function ChangeHeader()
{
var Parent = document.getElementById("<%=grv.ClientID %>");
var chkList = Parent.getElementsByTagName('input');
chkList[0].checked = true;
for (i = 1; i < chkList.length; i++) {
if (!chkList[i].checked) {
chkList[0].checked = false;
}
}
}
function SetCheckBoxes(chkHeader)
{
var Parent = document.getElementById("<%=grv.ClientID %>");
var chkList = Parent.getElementsByTagName('input');
if (chkHeader.checked) {
for (i = 0; i < chkList.length; i++) {
chkList[i].checked = true;
}
}
else {
for (i = 0; i < chkList.length; i++) {
chkList[i].checked = false;
}
}
}
</script>
On SAVE button click Check the check box Condition
protected void BtnSave_Click(object sender, EventArgs e)
{
int count = 0;
for (int i = 0; i < grv.Rows.Count; i++)
{
GridViewRow row = grv.Rows[i];
bool isChecked = ((CheckBox)row.FindControl("chkBox")).Checked;
if (isChecked)
{
count++;
}
}
if (count != 0)
{
SaveData(); //save the data to database
}
}
No comments:
Post a Comment