Monday, July 4, 2011

Delete checked Rows in Gridview

Step 1: Create aspx page like that :-


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CheckBoxinGriedview.aspx.cs"
    Inherits="WebApplication1.WebForm5" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        var TotalChkBx;
        var Counter;

        window.onload = function () {
            //Get total no. of CheckBoxes in side the GridView.
            TotalChkBx = parseInt('<%= this.gvCheckboxes.Rows.Count %>');

            //Get total no. of checked CheckBoxes in side the GridView.
            Counter = 0;
        }

        function HeaderClick(CheckBox) {
            //Get target base & child control.
            var TargetBaseControl =
       document.getElementById('<%= this.gvCheckboxes.ClientID %>');
            var TargetChildControl = "chkBxSelect";

            //Get all the control of the type INPUT in the base control.
            var Inputs = TargetBaseControl.getElementsByTagName("input");

            //Checked/Unchecked all the checkBoxes in side the GridView.
            for (var n = 0; n < Inputs.length; ++n)
                if (Inputs[n].type == 'checkbox' &&
                Inputs[n].id.indexOf(TargetChildControl, 0) >= 0)
                    Inputs[n].checked = CheckBox.checked;

            //Reset Counter
            Counter = CheckBox.checked ? TotalChkBx : 0;
        }

        function ChildClick(CheckBox, HCheckBox) {
            //get target control.
            var HeaderCheckBox = document.getElementById(HCheckBox);

            //Modifiy Counter; 
            if (CheckBox.checked && Counter < TotalChkBx)
                Counter++;
            else if (Counter > 0)
                Counter--;

            //Change state of the header CheckBox.
            if (Counter < TotalChkBx)
                HeaderCheckBox.checked = false;
            else if (Counter == TotalChkBx)
                HeaderCheckBox.checked = true;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvCheckboxes" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
            DataSourceID="SqlDataSource1" OnRowCreated="gvCheckboxes_RowCreated" OnRowDataBound="gvCheckboxes_RowDataBound">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="chkBxSelect" runat="server" />
                    </ItemTemplate>
                    <HeaderTemplate>
                        <asp:CheckBox ID="chkBxHeader" onclick="javascript:HeaderClick(this);" runat="server" />
                    </HeaderTemplate>
                </asp:TemplateField>
                <asp:BoundField HeaderText="id" DataField="id" SortExpression="id" InsertVisible="False"
                    ReadOnly="True" />
                <asp:BoundField DataField="article" HeaderText="article" SortExpression="article" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DemoConnectionString %>"
            SelectCommand="SELECT * FROM [blog]" 
            DeleteCommand="DELETE FROM [blog] WHERE [id] = @id" 
            InsertCommand="INSERT INTO [blog] ([article]) VALUES (@article)" 
            UpdateCommand="UPDATE [blog] SET [article] = @article WHERE [id] = @id">
            <DeleteParameters>
                <asp:Parameter Name="id" Type="Int32" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="article" Type="String" />
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="article" Type="String" />
                <asp:Parameter Name="id" Type="Int32" />
            </UpdateParameters>
        </asp:SqlDataSource>
        <asp:Button ID="Button1" runat="server" Text="Delete" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>


Step 2: Copy the following code in code behind :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


namespace WebApplication1
{
    public partial class WebForm5 : System.Web.UI.Page
    {
        string strConnection = ConfigurationManager.ConnectionStrings["DemoConnectionString"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }


 protected void Button1_Click(object sender, EventArgs e)
        {
            //StringBuilder str = new StringBuilder();

            // Select the checkboxes from the GridView control

            for (int i = 0; i < gvCheckboxes.Rows.Count; i++)
            {
                GridViewRow row = gvCheckboxes.Rows[i];
                bool isChecked = ((CheckBox)row.FindControl("chkBxSelect")).Checked;

                if (isChecked)
                {
                    // Column 2 is the name column
                    //str.Append(gvCheckboxes.Rows[i].Cells[1].Text + "<br>");
                    int employeeID = Convert.ToInt32(gvCheckboxes.DataKeys[row.RowIndex].Value);
                    // Pass the value of the selected Employye ID to the Delete //command.
                    //SqlDataSource1.DeleteParameters["id"].DefaultValue = employeeID.ToString();
                    //SqlDataSource1.Delete();
                    DeleteMultipleRecords(employeeID);
                 }
            }
            gvCheckboxes.DataBind();

            // prints out the result
            //Response.Write(str.ToString());
    }
        public void DeleteMultipleRecords(int id)
        {
            string cmd = "Delete blog where id=@Id";
            SqlConnection mycon = new SqlConnection(strConnection);
            SqlCommand mycmd = new SqlCommand(cmd, mycon);
            mycmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
            mycon.Open();
            mycmd.ExecuteNonQuery();

        }

        protected void gvCheckboxes_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            
                e.Row.Cells[1].Visible = false;
           

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                CheckBox chkBxSelect = (CheckBox)e.Row.Cells[0].FindControl("chkBxSelect");
                CheckBox chkBxHeader = (CheckBox)this.gvCheckboxes.HeaderRow.FindControl("chkBxHeader");
                chkBxSelect.Attributes["onclick"] = string.Format("javascript:ChildClick(this,'{0}');",chkBxHeader.ClientID);
            }
        }

        protected void gvCheckboxes_RowCreated(object sender, GridViewRowEventArgs e)
        {
            
        }
    }
}


No comments:

Post a Comment