Pages

Saturday 8 February 2014

Creating Asp.net Grid with CheckBox column and Action Column


with in the aspx page

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>

<%@ Page EnableEventValidation="false" Language="C#" AutoEventWireup="true" CodeBehind="grid1.aspx.cs"
    Inherits="aspsampleprj.grid1" %>

<!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>
    <link href="colorbox.css" rel="stylesheet" type="text/css" />
    <script src="jquery.min.js" type="text/javascript"></script>
    <script src="jquery.colorbox-min.js" type="text/javascript"></script>
    <%--<script type="text/javascript">
        $(function () {
            $("[id*=GridView1] td").hover(function () {
                $("td", $(this).closest("tr")).addClass("hover_row");
            }, function () {
                $("td", $(this).closest("tr")).removeClass("hover_row");
            });
        });
    </script>--%>
    <%--<script type="text/javascript">
        $(function () {
            $('#GridView1 tr').filter(':has(:checkbox:checked)').addClass('selected').end().click(function (event) {
                $(this).toggleClass('selected');
                if (event.target.type !== 'checkbox') {
                    $(':checkbox', this).attr('checked', function () {
                        return !this.checked;
                    });
                }
            });
            $("[id*=GridView1] td").hover(function () {
                $("td", $(this).closest("tr")).addClass("hover_row");
            }, function () {
                $("td", $(this).closest("tr")).removeClass("hover_row");
            });
            //            $("[id*=GridView1] td").bind("click", function () {
            //                var row = $(this).parent();
            //                $("[id*=GridView1] tr").each(function () {
            //                    if ($(this)[0] != row[0]) {
            //                        $("td", this).removeClass("selected_row");
            //                    }
            //                });
            //                $("td", row).each(function () {
            //                    if (!$(this).hasClass("selected_row")) {
            //                        $(this).addClass("selected_row");
            //                    } else {
            //                        $(this).removeClass("selected_row");
            //                    }
            //                });
            //            });
        });
    </script>--%>
    <script type="text/javascript">
        function Check_Click(objRef) {
            //Get the Row based on checkbox
            var row = objRef.parentNode.parentNode;
            if (objRef.checked) {
                //If checked change color to Aqua
                row.style.backgroundColor = "#EBF1FA";
            }
            else {
                //If not checked change back to original color
                if (row.rowIndex % 2 == 0) {
                    //Alternating Row Color
                    row.style.backgroundColor = "white";
                }
                else {
                    row.style.backgroundColor = "white";
                }
            }

            //Get the reference of GridView
            var GridView = row.parentNode;

            //Get all input elements in Gridview
            var inputList = GridView.getElementsByTagName("input");

            for (var i = 0; i < inputList.length; i++) {
                //The First element is the Header Checkbox
                var headerCheckBox = inputList[0];

                //Based on all or none checkboxes
                //are checked check/uncheck Header Checkbox
                var checked = true;
                if (inputList[i].type == "checkbox" && inputList[i] != headerCheckBox) {
                    if (!inputList[i].checked) {
                        checked = false;
                        break;
                    }
                }
            }
            headerCheckBox.checked = checked;

        }
    </script>
    <script type="text/javascript">
        function checkAll(objRef) {
            var GridView = objRef.parentNode.parentNode.parentNode;
            var inputList = GridView.getElementsByTagName("input");
            for (var i = 0; i < inputList.length; i++) {
                //Get the Cell To find out ColumnIndex
                var row = inputList[i].parentNode.parentNode;
                if (inputList[i].type == "checkbox" && objRef != inputList[i]) {
                    if (objRef.checked) {
                        //If the header checkbox is checked
                        //check all checkboxes
                        //and highlight all rows
                        row.style.backgroundColor = "#EBF1FA";
                        inputList[i].checked = true;
                    }
                    else {
                        //If the header checkbox is checked
                        //uncheck all checkboxes
                        //and change rowcolor back to original
                        if (row.rowIndex % 2 == 0) {
                            //Alternating Row Color
                            row.style.backgroundColor = "white";
                        }
                        else {
                            row.style.backgroundColor = "white";
                        }
                        inputList[i].checked = false;
                    }
                }
            }
        }
    </script>
    <script type="text/javascript">
        function MouseEvents(objRef, evt) {
            var checkbox = objRef.getElementsByTagName("input")[0];
            if (evt.type == "mouseover") {
                objRef.style.backgroundColor = "#e7e7e7";
            }
            else {
                if (checkbox.checked) {
                    objRef.style.backgroundColor = "#EBF1FA";
                }
                else if (evt.type == "mouseout") {
                    if (objRef.rowIndex % 2 == 0) {
                        //Alternating Row Color
                        objRef.style.backgroundColor = "white";
                    }
                    else {
                        objRef.style.backgroundColor = "white";
                    }
                }
            }
        }
    </script>
    <style type="text/css">
        .hover_row
        {
            background-color: #e7e7e7;
        }
        .selected
        {
            background-color: #EBF1FA;
        }
        .Button:hover, .MyButton:hover, .DeleteBtn:hover
        {
            background-color: #ddecfe;
        }
        .MyButton
        {
            border: 2px solid #D2E1F4;
            border-radius: 10px;
            color: #04408C;
            font-weight: bold;
            padding: 5px 5px 5px 5px;
            background-image: url(plus.png);
            background-repeat: no-repeat;
            background-position-y: 5px;
            background-position-x: 10px;
            background-color: #e7e7e7;
        }
        .Button
        {
            border: 2px solid #D2E1F4;
            border-radius: 10px;
            color: #04408C;
            font-weight: bold;
            padding: 5px 5px 5px 5px;
            background-color: #e7e7e7;
        }
        .DeleteBtn
        {
            border: 2px solid #D2E1F4;
            border-radius: 10px;
            color: #04408C;
            font-weight: bold;
            padding: 5px 5px 5px 5px;
            background-image: url(Delete.gif);
            background-repeat: no-repeat;
            background-position-y: 5px;
            background-position-x: 10px;
            background-color: #e7e7e7;
        }
        .modalBackground
        {
            background-color: Gray;
            filter: alpha(opacity=80);
            opacity: 0.8;
            z-index: 10000;
        }
     
        #GridView1 tr.rowHover:hover
        {
            text-decoration: none !important;
            background-color: #e7e7e7;
            filter: alpha(opacity=100);
            opacity: 1;
        }
    </style>
    <script language="javascript" type="text/javascript">
        //        function CheckAllEmp(Checkbox) {
        //            var GridVwHeaderChckbox = document.getElementById("<%=GridView1.ClientID %>");
        //            for (i = 1; i < GridVwHeaderChckbox.rows.length; i++) {
        //                GridVwHeaderChckbox.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = Checkbox.checked;
        //            }
        //        }
        //        function CheckAllEmp(objRef) {
        //            var GridView = objRef.parentNode.parentNode.parentNode;
        //            var inputList = GridView.getElementsByTagName("input");
        //            for (var i = 0; i < inputList.length; i++) {
        //                //Get the Cell To find out ColumnIndex
        //                var row = inputList[i].parentNode.parentNode;
        //                if (inputList[i].type == "checkbox" && objRef != inputList[i]) {
        //                    if (objRef.checked) {
        //                        //If the header checkbox is checked
        //                        //check all checkboxes
        //                        //and highlight all rows
        //                        row.style.backgroundColor = "#EBF1FA";
        //                        inputList[i].checked = true;
        //                    }
        //                    else {
        //                        //If the header checkbox is checked
        //                        //uncheck all checkboxes
        //                        //and change rowcolor back to original

        //                        row.style.backgroundColor = "white";
        //                        inputList[i].checked = false;
        //                    
        //                    }
        //                }
        //            }
        //        }
        function RowValues(fname, lname, age, id) {
            // alert(id);
            //alert('FirstName:' + fname + ' LastName:' + lname + ' Age:' + age);
            document.getElementById("txt_UserFName").value = fname;
            document.getElementById("txt_UserLName").value = lname;
            document.getElementById("txt_UserAge").value = age;
        }
        function closepopup() {
            $find('ModalPopupExtender1').hide();
            $find('ModalPopupExtender2').hide();
        }
        function OpenReport(winURL, winWidth, winHeight) {
            $.colorbox({ href: winURL, iframe: true, width: winWidth, height: winHeight, onClosed: function () {
                location.reload(true);
            }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <ajax:ToolkitScriptManager ID="ScriptManager1" runat="server">
    </ajax:ToolkitScriptManager>
    <div id="DivContent">
        <asp:UpdatePanel ID="updatepnl1" runat="server">
            <ContentTemplate>
                <asp:Button ID="btn_Add" Text="Add" runat="server" Width="100" CssClass="MyButton"
                    OnClick="btn_Add_Click"></asp:Button>
                &nbsp;<asp:Button ID="btn_Delete" Text="Delete" runat="server" Width="100" CssClass="DeleteBtn"
                    OnClick="btn_Delete_Click"></asp:Button>
                <asp:GridView ID="GridView1" HeaderStyle-BackColor="#D2E1F4" HeaderStyle-ForeColor="#04408C"
                    OnRowDataBound="RowDataBound" OnRowCommand="GridView1_RowCommand" OnRowUpdating="GridView1_RowUpdating" Width="100%" BackColor="White" BorderColor="#D2E1F4"
                    BorderStyle="Solid" BorderWidth="5px" CellPadding="3" GridLines="Horizontal"
                    runat="server" AutoGenerateColumns="false" DataKeyNames="Id">
                    <AlternatingRowStyle BackColor="#F7F7F7" />
                    <Columns>
                        <asp:ButtonField Text="SingleClick" CommandName="SingleClick" Visible="False" />
                        <asp:TemplateField HeaderStyle-Width="1%" ItemStyle-Width="1%" FooterStyle-Width="1%">
                            <HeaderTemplate>
                                <asp:CheckBox ID="chkboxSelectAll" runat="server" onclick="checkAll(this);" />
                            </HeaderTemplate>
                            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                            <ItemTemplate>
                                <asp:CheckBox ID="chkbox" runat="server" onclick="Check_Click(this);"></asp:CheckBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderStyle-Width="1%" ItemStyle-Width="1%" FooterStyle-Width="1%">
                            <ItemTemplate>
                                <asp:ImageButton ID="Image_Edit" runat="server" ImageUrl="task16.png" OnClientClick='<%# String.Format("javascript:return OpenReport(\"UserForm.aspx?cid={0}\",500,400)", Eval("Id")) %>'
                                    ToolTip="Edit" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderStyle-Width="1%" ItemStyle-Width="1%" FooterStyle-Width="1%">
                            <ItemTemplate>
                                <asp:ImageButton ID="Image_Del" runat="server" ImageUrl="Delete.gif" OnClick="imgbtn_Delete_Click"
                                    ToolTip="Delete" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <%--<asp:BoundField DataField="Id" Visible="false"/>--%>
                        <asp:TemplateField HeaderText="First Name" HeaderStyle-Width="25%" ItemStyle-Width="25%" FooterStyle-Width="25%">
                            <ItemTemplate>
                                <asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>'></asp:Label>
                                <asp:TextBox ID="FirstName" runat="server" Text='<%# Eval("FirstName") %>' Width="175px" Visible="false"></asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <%--<asp:BoundField HeaderStyle-Width="25%" ItemStyle-Width="25%" FooterStyle-Width="25%"
                            DataField="FirstName" HeaderText="First Name" />--%>
                            <asp:TemplateField HeaderText="Last Name" HeaderStyle-Width="25%" ItemStyle-Width="25%" FooterStyle-Width="25%">
                            <ItemTemplate>
                                <asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>'></asp:Label>
                                <asp:TextBox ID="LastName" runat="server" Text='<%# Eval("LastName") %>' Width="175px"
                                    Visible="false"></asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <%--<asp:BoundField HeaderStyle-Width="25%" ItemStyle-Width="25%" FooterStyle-Width="25%"
                            DataField="LastName" HeaderText="Last Name" />--%>
                              <asp:TemplateField HeaderText="Age" HeaderStyle-Width="10%" ItemStyle-Width="10%" FooterStyle-Width="10%" ItemStyle-HorizontalAlign="Center">
                            <ItemTemplate>
                                <asp:Label ID="AgeLabel" runat="server" Text='<%# Eval("Age") %>'></asp:Label>
                                <asp:TextBox ID="Age" runat="server" Text='<%# Eval("Age") %>' Width="175px"
                                    Visible="false"></asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <%--<asp:BoundField HeaderStyle-Width="10%" ItemStyle-Width="10%" FooterStyle-Width="10%"
                            DataField="Age" HeaderText="Age" ItemStyle-HorizontalAlign="Center" />--%>
                    </Columns>
                </asp:GridView>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:Label ID="lbl_FName" Text="First Name" runat="server"></asp:Label>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:TextBox ID="txt_UserFName" runat="server" Width="150"></asp:TextBox>
                <br />
                <br />
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:Label ID="lbl_LName" Text="Last Name" runat="server"></asp:Label>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:TextBox ID="txt_UserLName" runat="server" Width="150"></asp:TextBox>
                <br />
                <br />
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:Label ID="lbl_Age" Text="Age" runat="server"></asp:Label>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:TextBox ID="txt_UserAge" runat="server" Width="150"></asp:TextBox>
                <%--<asp:LinkButton ID="lnkDummy" runat="server"></asp:LinkButton>--%>
                <asp:Label ID="lblresult" runat="server" />
                <asp:Button ID="btnShowPopup" runat="server" Style="display: none" />
                <ajax:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="btnShowPopup"
                    PopupControlID="pnlpopup" CancelControlID="btnNo" BackgroundCssClass="modalBackground">
                </ajax:ModalPopupExtender>
                <asp:Panel ID="pnlpopup" runat="server" BackColor="White" Height="100px" Width="400px"
                    Style="display: none">
                    <table width="100%" style="border: Solid 2px #3AC0F2; width: 100%; height: 100%"
                        cellpadding="0" cellspacing="0">
                        <tr style="background-color: #3AC0F2">
                            <td style="height: 10%; color: White; font-weight: bold; padding: 3px; font-size: larger;
                                font-family: Calibri" align="Left">
                                Confirm Box
                            </td>
                            <td style="color: White; font-weight: bold; padding: 3px; font-size: larger" align="Right">
                                <a href="javascript:void(0)" onclick="closepopup()">
                                    <img src="close.png" style="border: 0px" align="right" /></a>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2" align="left" style="padding: 5px; font-family: Calibri">
                                <asp:Label ID="lblUser" runat="server" />
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                            </td>
                        </tr>
                        <tr>
                            <td>
                            </td>
                            <td align="right" style="padding-right: 15px">
                                <asp:ImageButton ID="btnYes" OnClick="btnYes_Click" runat="server" ImageUrl="yes.png"
                                    ToolTip="Yes" />
                                <asp:ImageButton ID="btnNo" runat="server" ImageUrl="No.png" ToolTip="No" />
                            </td>
                        </tr>
                    </table>
                </asp:Panel>
                <asp:Button ID="btnShowDelPopup" runat="server" Style="display: none" />
                <ajax:ModalPopupExtender ID="ModalPopupExtender2" runat="server" TargetControlID="btnShowDelPopup"
                    PopupControlID="pnlDelpopup" CancelControlID="btnNo" BackgroundCssClass="modalBackground">
                </ajax:ModalPopupExtender>
                <asp:Panel ID="pnlDelpopup" runat="server" BackColor="White" Height="100px" Width="400px"
                    Style="display: none">
                    <table width="100%" style="border: Solid 2px #3AC0F2; width: 100%; height: 100%"
                        cellpadding="0" cellspacing="0">
                        <tr style="background-color: #3AC0F2">
                            <td style="height: 10%; color: White; font-weight: bold; padding: 3px; font-size: larger;
                                font-family: Calibri" align="Left">
                                Message
                            </td>
                            <td style="color: White; font-weight: bold; padding: 3px; font-size: larger" align="Right">
                                <a href="javascript:void(0)" onclick="closepopup()">
                                    <img src="close.png" style="border: 0px" align="right" /></a>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2" align="left" style="padding: 5px; font-family: Calibri">
                                <asp:Label ID="Label2" runat="server" />
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2" align="center">
                                <asp:Button runat="server" Width="100" CssClass="Button" Text="ok" />
                            </td>
                        </tr>
                    </table>
                </asp:Panel>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

with in the 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.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;

namespace aspsampleprj
{
    public partial class grid1 : System.Web.UI.Page
    {
        private const int _firstEditCellIndex = 2;
        string ConString = ConfigurationManager.ConnectionStrings["sampleasp"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadGrid();
                //BindGridwithheader();
            }
        }

        public void LoadGrid() {
            using (SqlConnection con = new SqlConnection(ConString))
            {
                const string SP = "select pid,firstname,lastname,age from person2";
                List<UserDetails> UsersList = new List<UserDetails>();
                con.Open();
                using (SqlCommand cmd = new SqlCommand(SP, con))
                {
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            UserDetails data = new UserDetails();
                            data.Id = reader.IsDBNull(reader.GetOrdinal("pid")) ? 0 : reader.GetInt32(reader.GetOrdinal("pid"));
                            data.FirstName = reader.IsDBNull(reader.GetOrdinal("FirstName")) ? string.Empty : reader.GetString(reader.GetOrdinal("FirstName"));
                            data.LastName = reader.IsDBNull(reader.GetOrdinal("LastName")) ? string.Empty : reader.GetString(reader.GetOrdinal("LastName"));
                            data.Age = reader.IsDBNull(reader.GetOrdinal("Age")) ? 0 : reader.GetInt32(reader.GetOrdinal("Age"));
                            UsersList.Add(data);
                        }
                    }
                }
                GridView1.DataSource = UsersList;
                GridView1.DataBind();
                if (GridView1.Rows.Count == 0)
                {
                    BindGridwithheader();

                }
            }
        }

        private void BindGridwithheader()
        {
            DataTable _dt = null;
            try
            {
                //string constring = ConfigurationManager.ConnectionStrings["MySQLConnectionString"].ConnectionString;
                SqlConnection _con = new SqlConnection(ConString);
                SqlCommand _cmd = new SqlCommand();
                SqlDataAdapter _da = new SqlDataAdapter();
                _dt = new DataTable();

                if (_con.State == ConnectionState.Closed)
                    _con.Open();
                _cmd.CommandText = "select * from person2";
                _cmd.Connection = _con;
                _da.SelectCommand = _cmd;
                _da.Fill(_dt);

                GridView1.DataSource = _dt;
                GridView1.DataBind();
                if (GridView1.Rows.Count == 0)
                {
                    EmptyGridFix(GridView1);

                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }
        protected void EmptyGridFix(GridView grdView)
    {
        try
        {
            if(grdView.Rows.Count == 0 &&
                grdView.DataSource != null)
            {
                DataTable dt = null;
                if(grdView.DataSource is DataSet)
                {
                    dt = ((DataSet)grdView.DataSource).Tables[0].Clone();
                }
                else if (grdView.DataSource is DataTable)
                    dt = ((DataTable)grdView.DataSource).Clone();

                if(dt == null)
                    return;

                dt.Rows.Add(dt.NewRow()); // add empty row
                grdView.DataSource = dt;
                grdView.DataBind();

                // hide row
                grdView.Rows[0].Visible = false;
                grdView.Rows[0].Controls.Clear();
            }

            // normally executes at all postbacks
            if(grdView.Rows.Count == 1 &&
                grdView.DataSource == null)
            {
                bool bIsGridEmpty = true;

                // check first row that all cells empty
                for(int i = 0; i < grdView.Rows[0].Cells.Count; i++)
                {
                    if(grdView.Rows[0].Cells[i].Text != string.Empty)
                    {
                        bIsGridEmpty = false;
                    }
                }
                // hide row
                if(bIsGridEmpty)
                {
                    grdView.Rows[0].Visible = false;
                    grdView.Rows[0].Controls.Clear();
                }
            }
        }
        catch (Exception ex)
        {
            ex.Message.ToString();
        }
    }

        //protected void OnRowCreated(object sender, GridViewRowEventArgs e)
        //{
        //    if (e.Row.RowType == DataControlRowType.DataRow)
        //    {
        //        //On Mouse over highlight gridview
        //        e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#e7e7e7'");
        //        e.Row.Attributes.Add("onclick", "this.style.backgroundColor='#D2E1F4'");
        //        //On Mouse out restore girdview row color based on alternate row color//Please change this color with your gridview alternate color.
        //        if (e.Row.RowIndex % 2 == 0)
        //        {

        //            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#F7F7F7'");
        //        }
        //        else
        //        {
        //            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
        //        }
        //    }
        //}

        protected void RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
                // Get the javascript which is assigned to this LinkButton
                string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");

                // If the page contains validator controls then call
                // Page_ClientValidate before allowing a cell to be edited
                //if (Page.Validators.Count > 0)
                //    _jsSingle = _jsSingle.Insert(11, "if(Page_ClientValidate())");

                // Add events to each editable cell
                for (int columnIndex = _firstEditCellIndex; columnIndex < e.Row.Cells.Count; columnIndex++)
                {
                    // Add the column index as the event argument parameter
                    string js = _jsSingle.Insert(_jsSingle.Length - 2, columnIndex.ToString());
                    // Add this javascript to the onclick Attribute of the cell
                    e.Row.Cells[columnIndex].Attributes["onclick"] = js;
                    // Add a cursor style to the cells
                    e.Row.Cells[columnIndex].Attributes["style"] += "cursor:pointer;cursor:hand;";
                }
                object objTemp = GridView1.DataKeys[e.Row.RowIndex].Value as object;
                string id="";
                if (objTemp != null)
                {
                    id = objTemp.ToString();
                    //Do your operations
                }
                TextBox FNamelb = (TextBox)e.Row.FindControl("FirstName");
                TextBox LNamelb = (TextBox)e.Row.FindControl("LastName");
                TextBox Agelb = (TextBox)e.Row.FindControl("Age");
                string FName = FNamelb.Text.ToUpper();
                string LName = LNamelb.Text.ToUpper();
                string Age = Agelb.Text.ToUpper();
                //string FName = e.Row.Cells[4].Text.ToUpper();
                //string LName = e.Row.Cells[5].Text.ToUpper();
                //string Age = e.Row.Cells[6].Text.ToUpper();
                //lblresult.Text = RowVal;
                e.Row.Attributes.Add("onclick", "RowValues('" + FName + "','" + LName + "','" + Age + "','" + id + "');");
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
            }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            GridView _gridView = (GridView)sender;

            switch (e.CommandName)
            {
                case ("SingleClick"):
                    // Get the row index
                    int _rowIndex = int.Parse(e.CommandArgument.ToString());
                    // Parse the event argument (added in RowDataBound) to get the selected column index
                    int _columnIndex = int.Parse(Request.Form["__EVENTARGUMENT"]) <4 ? 4 : int.Parse(Request.Form["__EVENTARGUMENT"]);
                    // Set the Gridview selected index
                    _gridView.SelectedIndex = _rowIndex;
                    // Bind the Gridview
                    //_gridView.DataSource = _sampleData;
                    //_gridView.DataBind();

                    // Write out a history if the event
                    //this.Message.Text += "Single clicked GridView row at index " + _rowIndex.ToString()
                    //    + " on column index " + _columnIndex + "<br />";

                    // Get the display control for the selected cell and make it invisible
                    Control _displayControl = _gridView.Rows[_rowIndex].Cells[_columnIndex].Controls[1];
                    _displayControl.Visible = false;
                    // Get the edit control for the selected cell and make it visible
                    Control _editControl = _gridView.Rows[_rowIndex].Cells[_columnIndex].Controls[3];
                    _editControl.Visible = true;
                    // Clear the attributes from the selected cell to remove the click event
                    _gridView.Rows[_rowIndex].Cells[_columnIndex].Attributes.Clear();

                    // Set focus on the selected edit control
                    ScriptManager.RegisterStartupScript(this, GetType(), "SetFocus",
                        "document.getElementById('" + _editControl.ClientID + "').focus();", true);
                    // If the edit control is a dropdownlist set the
                    // SelectedValue to the value of the display control
                    if (_editControl is DropDownList && _displayControl is Label)
                    {
                        ((DropDownList)_editControl).SelectedValue = ((Label)_displayControl).Text;
                    }
                    // If the edit control is a textbox then select the text
                    if (_editControl is TextBox)
                    {
                        ((TextBox)_editControl).Attributes.Add("onfocus", "this.select()");
                    }
                    // If the edit control is a checkbox set the
                    // Checked value to the value of the display control
                    if (_editControl is CheckBox && _displayControl is Label)
                    {
                        ((CheckBox)_editControl).Checked = bool.Parse(((Label)_displayControl).Text);
                    }

                    break;
            }
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridView _gridView = (GridView)sender;

            if (e.RowIndex > -1)
            {
                // Loop though the columns to find a cell in edit mode
                for (int i = _firstEditCellIndex; i < _gridView.Columns.Count; i++)
                {
                    // Get the editing control for the cell
                    Control _editControl = _gridView.Rows[e.RowIndex].Cells[i].Controls[3];
                    if (_editControl.Visible)
                    {
                        int _dataTableColumnIndex = i - 1;

                        try
                        {
                            // Get the id of the row
                            Label idLabel = (Label)_gridView.Rows[e.RowIndex].FindControl("IdLabel");
                            int id = int.Parse(idLabel.Text);
                            // Get the value of the edit control and update the DataTable
                            //DataTable dt = _sampleData;
                            //DataRow dr = dt.Rows.Find(id);
                            //dr.BeginEdit();
                            //if (_editControl is TextBox)
                            //{
                            //    dr[_dataTableColumnIndex] = ((TextBox)_editControl).Text;
                            //}
                            //else if (_editControl is DropDownList)
                            //{
                            //    dr[_dataTableColumnIndex] = ((DropDownList)_editControl).SelectedValue;
                            //}
                            //else if (_editControl is CheckBox)
                            //{
                            //    dr[_dataTableColumnIndex] = ((CheckBox)_editControl).Checked;
                            //}
                            //dr.EndEdit();

                            // Save the updated DataTable
                          //  _sampleData = dt;

                            // Clear the selected index to prevent
                            // another update on the next postback
                            _gridView.SelectedIndex = -1;
                            LoadGrid();
                            // Repopulate the GridView
                          //  _gridView.DataSource = dt;
                           // _gridView.DataBind();
                        }
                        catch (ArgumentException)
                        {
                            //this.Message.Text += "Error updating GridView row at index "
                            //    + e.RowIndex + "<br />";

                            //// Repopulate the GridView
                            //_gridView.DataSource = _sampleData;
                            //_gridView.DataBind();
                        }
                    }
                }
            }
        }

        //protected void OnRowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        //{
        //    if (e.Row.RowType == DataControlRowType.DataRow)
        //    {
        //        foreach (GridViewRow row in GridView1.Rows)
        //        {
        //            CheckBox chk = (CheckBox)e.Row.FindControl("chkbox");
        //            e.Row.Attributes.Add("onclick", "this.style.backgroundColor='#D2E1F4'");

        //            // e.Row.Attributes.Add("OnClick", "RowClicked(" + chk.ClientID + ")");
        //        }
        //        //if (e.Row.RowIndex % 2 == 0)
        //        //{
        //        //    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#F7F7F7'");
        //        //}
        //        //e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex);
        //        //e.Row.ToolTip = "Click to select this row.";
        //        //e.Row.Attributes.Add("onclick", "this.style.backgroundColor='#D2E1F4'");
        //    }
        //}

        //protected void OnSelectedIndexChanged(object sender, EventArgs e)
        //{
        //    foreach (GridViewRow row in GridView1.Rows)
        //    {
        //        if (row.RowIndex == GridView1.SelectedIndex)
        //        {
        //            row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
        //            row.ToolTip = string.Empty;
        //        }
        //        else
        //        {
        //            row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
        //            row.ToolTip = "Click to select this row.";
        //        }
        //    }
        //}

        protected void btn_Add_Click(object sender, EventArgs e)
        {
            Response.Redirect("UserForm.aspx");
            //btn_Add.Attributes["OnClick"] = "OpenReport('UserForm.aspx',500,500);";
        }

        protected void imgbtn_Edit_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton btndetails = sender as ImageButton;
            GridViewRow gvrow = (GridViewRow)btndetails.NamingContainer;
            int userid = int.Parse(GridView1.DataKeys[gvrow.RowIndex].Values["Id"].ToString());
           
        }


        protected void btn_Delete_Click(object sender, EventArgs e)
        {
            int result=0;
            // Iterate through the Products.Rows property
            foreach (GridViewRow row in GridView1.Rows)
            {
                // Access the CheckBox
                CheckBox cb = (CheckBox)row.FindControl("chkbox");
                if (cb != null && cb.Checked)
                {
                    int pID =
                        Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
                   
                    using (SqlConnection con = new SqlConnection(ConString))
                    {
                        con.Open();
                        string SP = "Delete from person2 where pid=" + pID + "";

                        using (SqlCommand cmd = new SqlCommand(SP, con))
                        {
                            cmd.CommandType = CommandType.Text;
                            result = (int)cmd.ExecuteNonQuery();

                        }
                    }
                }
            }
            if (result == 1)
            {
                LoadGrid();
            }
            else
            {
                Label2.Text = "Please Select the Record to Delete";
                ModalPopupExtender2.Show();
            }
           
        }


        protected void btnYes_Click(object sender, ImageClickEventArgs e)
        {
            int result;
            using (SqlConnection con = new SqlConnection(ConString))
            {
                try
                {
                    con.Open();
                    int userid = Convert.ToInt32(Session["Id"]);
                    string SP = "Delete from person2 where pid=" + userid + "";

                    using (SqlCommand cmd = new SqlCommand(SP, con))
                    {
                        cmd.CommandType = CommandType.Text;
                        result = (int)cmd.ExecuteNonQuery();

                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }

            }
            if (result == 1)
            {

                //Displaying alert message after successfully deletion of user
                // ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + username + " details deleted successfully')", true);
                LoadGrid();
            }
        }

        protected void imgbtn_Delete_Click(object sender, ImageClickEventArgs e)
        {
           
            ImageButton btndetails = sender as ImageButton;
            GridViewRow gvrow = (GridViewRow)btndetails.NamingContainer;
            int userid = int.Parse(GridView1.DataKeys[gvrow.RowIndex].Values["Id"].ToString());
            //string username = gvrow.Cells[2].Text;
            Session["Id"] = GridView1.DataKeys[gvrow.RowIndex].Value.ToString();
            Session["FirstName"] = gvrow.Cells[2].Text;
            lblUser.Text = "Are you sure you want to delete " + Session["UserName"] + " Details?";
            ModalPopupExtender1.Show();
           
         
            //Response.Redirect("grid1.aspx");
        }
    }
}

No comments:

Post a Comment