In this article we will see how we can check and uncheck checkbox in gridview using jQuery. Using jQuery we can achieve this without any for loop and writing very minimal code. Let's see how we can do this. Step 1: Add below code snippet in the code behind file to fetch the data from SQL and bind the data to gridview. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string strQuery = "SELECT * FROM Recipie"; gvParent.DataSource = GetData(strQuery); gvParent.DataBind(); } } private SqlConnection GetConnection(string m_conString) { SqlConnection con = new SqlConnection(m_conString); return con; }
private DataTable GetData(string strQuery) { string m_conString = CryptographyHelper.Decrypt(ConfigurationSettings.AppSettings["DBConnectionString"]); DataTable dtDept = null; SqlConnection con = GetConnection(m_conString); using (con) { con.Open(); using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(strQuery, con)) { dtDept = new DataTable(); sqlAdapter.Fill(dtDept); } } return dtDept; } Step 2: Add jquery-1.4.2.js in the head section of aspx page. <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script> Step 3: Add below grid inside the div of form tag. I have added 'dummychkstyle' class for the checkboxes. <asp:GridView ID="gvParent" runat="server" AutoGenerateColumns="False" ShowHeader="True"> <HeaderStyle HorizontalAlign="Left" Height="20px" BackColor="#880015" ForeColor="#ffffff" Font-Bold="true" Font-Size=".75em" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" /> <Columns> <asp:TemplateField> <HeaderTemplate> <asp:CheckBox ID="checkAll" runat="server" onclick="CheckAll(this);" /> </HeaderTemplate> <ItemTemplate> <input type="checkbox" class="dummychkstyle" id="chkSelect" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField HeaderText="By" DataField="By" SortExpression="EmployeeId"> <ItemStyle HorizontalAlign="Center" Width="140px" /> </asp:BoundField> <asp:BoundField HeaderText="Recipie Name" DataField="RecipieName" SortExpression="EmployeeName"> <ItemStyle HorizontalAlign="Center" Width="180px" /> </asp:BoundField> <asp:BoundField HeaderText="Preparation Time" DataField="PreparationTime" SortExpression="Designation"> <ItemStyle HorizontalAlign="Center" Width="140px" /> </asp:BoundField> <asp:BoundField HeaderText="Cooking Time" DataField="CookingTime" SortExpression="Location"> <ItemStyle HorizontalAlign="Center" Width="120px" /> </asp:BoundField> </Columns> </asp:GridView>
Step 4: Place below javascript in the aspx page. The 'dummychkstyle' class will be used to identify the checkboxes. <script language="javascript" type="text/javascript"> function CheckAll(selectChk) { if ($(selectChk).attr('checked')) { $(".dummychkstyle").attr('checked', true); } else { $(".dummychkstyle").attr('checked', false); } } </script>
Live Demo
This ends the article of selecting checkbox of gridview usin jQuery
|