ASP.NET  

Single Click on GridView Row To Redirect and bind Row values in another Page


This code is used to Redirect to another page when User click on the GRIDVIEW ROW.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" EnableEventValidation="false"%>

<%@ Register TagName="Header" TagPrefix="Uc1" Src="~/UserControl/Header.ascx" %>

<!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">

 

//This function will fire when user Click on the GRID VIEW ROW

var NAC_TimeoutId = null;

function NAC_StartSingleClick(event)

{

    NAC_TimeoutId = setTimeout(event, 200);

 

}

var previousRow;

function NAC_StartDblClick(event)

{

    window.clearTimeout(NAC_TimeoutId);

    setTimeout(event, 1);

}

function ChangeRowColor(row) {

    //If last clicked row and the current clicked row are same

    if (previousRow == row)

        return; //do nothing

    //If there is row clicked earlier

    else if (previousRow != null)

        document.getElementById(previousRow).style.backgroundColor = "#ffffff"; //change the color of the previous row back to white

 

    document.getElementById(row).style.backgroundColor = "#ffffda"; //change the color of the current row to light yellow

 

    //assign the current row id to the previous row id for next row to be clicked

    previousRow = row;

}

function RowColor(row)

 {

 

}

//This Function is used to change the ROW backGroundColor on MouseOver.

var lastColorUsed;

function NAC_ChangeBackColor(row, highlight, RowHighlightColor)

{

    if (highlight)

    {

        // set the background colour

        lastColorUsed = row.style.backgroundColor;

        row.style.backgroundColor = RowHighlightColor;

    }

    else

    {

        // restore the colour

        row.style.backgroundColor = lastColorUsed;

    }

} 

 

</script>

</head>

<body>

    <form id="form1" runat="server">

    <div style="height: 554px; width: 1088px; margin-bottom: 91px;">

    <Uc1:Header ID="test" runat="server" Visible="true" />

    <table>

    <tr>

    <td>

        <asp:ScriptManager ID="ScriptManager1" runat="server">

        </asp:ScriptManager>

   

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">

        <ContentTemplate>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

           

            style="top: 177px; left: 394px; position: absolute; height: 198px; width: 531px"

            onrowupdated="GridView1_RowUpdated" onrowupdating="GridView1_RowUpdating"

            onrowcancelingedit="GridView1_RowCancelingEdit" DataKeyNames="Sno"

            onrowediting="GridView1_RowEditing"

            onrowdatabound="GridView1_RowDataBound"

            onselectedindexchanged="GridView1_SelectedIndexChanged"

            onselectedindexchanging="GridView1_SelectedIndexChanging"

            ondatabound="GridView1_DataBound" onrowcommand="GridView1_RowCommand"

            onprerender="GridView1_PreRender">

           

        <Columns>

        <asp:ButtonField Text="SingleClick" CommandName="SingleClick" Visible="false" />

        <asp:ButtonField Text="DoubleClick" CommandName="DoubleClick"

                            Visible="false" />

        <asp:TemplateField HeaderText="ENo.">

        <ItemTemplate>

        <%#Eval("Sno")%>

        </ItemTemplate>

        </asp:TemplateField>

        <asp:TemplateField HeaderText="Name">

        <ItemTemplate>

        <%#Eval("Name")%>

        </ItemTemplate>

        </asp:TemplateField>

        <asp:TemplateField HeaderText="Salary">

        <ItemTemplate>

        <%#Eval("Salary")%>

        </ItemTemplate>

        </asp:TemplateField>

        <asp:TemplateField HeaderText="DeptNo">

        <ItemTemplate>

        <%#Eval("DeptNo")%>

        </ItemTemplate>

        </asp:TemplateField>

        <asp:TemplateField HeaderText="Address">

        <ItemTemplate>

        <%#Eval("Address")%>

        </ItemTemplate>

        </asp:TemplateField>

       

        <asp:TemplateField HeaderText="Country">

        <ItemTemplate>

        <%#Eval("Country")%>

        </ItemTemplate>

        </asp:TemplateField>

       

        <asp:TemplateField HeaderText="State">

        <ItemTemplate>

        <%#Eval("State")%>

        </ItemTemplate>

        </asp:TemplateField>

       

        <asp:TemplateField HeaderText="City">

        <ItemTemplate>

        <%#Eval("City")%>

        </ItemTemplate>

        </asp:TemplateField>       

            <asp:TemplateField HeaderText="Image">

        <ItemTemplate>

      <asp:Image ID="main" runat="server" Height="100" Width="100"/>

        </ItemTemplate>

        </asp:TemplateField>       

      

     <%-- <asp:TemplateField HeaderText="Edit">

      <ItemTemplate>

      <a id="Edit" visible="true" href="Employee.aspx?ID=<%#Eval("Sno")%>">Edit</a>

      </ItemTemplate>

      </asp:TemplateField>--%>          

       

        </Columns>

            <SelectedRowStyle BackColor="#FF66FF" />

            <EditRowStyle BackColor="Fuchsia" />

        </asp:GridView>

        </ContentTemplate>

        </asp:UpdatePanel>

        </td>

    </tr>

    </table>

    </div>

    </form>

</body>

</html>


Code Behind File:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

public partial class _Default : System.Web.UI.Page

{

    DataSet ds = new DataSet();

    protected void Page_Load(object sender, EventArgs e)

    {

          if(!this.IsPostBack)

            {

 

                BindGrid();

            }  

     }

//This method is used to bind Table to GridView

    private void BindGrid()

    {

        SqlConnection con = new SqlConnection("");

        SqlDataAdapter da = new SqlDataAdapter("select * from emp", con);

        da.Fill(ds, "Emp");

        GridView1.DataSource = ds;

        GridView1.DataBind();

 

    }

    protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)

    {

       

    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {

        //int no = Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells[0].Text);

    }

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

    {

 

    }

    //This event will fire after the single click on Grid Row

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

    {

        int id =Convert.ToInt32(GridView1.DataKeys[e.NewEditIndex].Value);

       Response.Redirect("Employee.aspx?ID="+id+"");       

    }

    //This event will use to bind GridRows if UserClicks on the row ROWDATABOUND event will b fired 

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {    

        try

        {

            if (e.Row.RowType == DataControlRowType.DataRow)

            {

//This is used to Bind IMAGES on GRIDVIEW column

                DataRowView drview = (DataRowView)e.Row.DataItem;

                ((Image)e.Row.FindControl("main")).ImageUrl = "~/Images/" + drview.Row.ItemArray[8].ToString();

 

                LinkButton _doubleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];

                string _jsDouble = ClientScript.GetPostBackClientHyperlink(_doubleClickButton, "");

                e.Row.Attributes["ondblclick"] = _jsDouble;

                e.Row.Attributes["onmouseover"] = "javascript:return setMouseOverColor(this);";

                e.Row.Attributes["onmouseout"] = "javascript:return setMouseOutColor(this);";

                //Newly changed

               //e.Row.Attributes.Add("onclick", "javascript:ChangeRowColor('" + e.Row.ClientID + "')");

            }

            if (e.Row.RowType == DataControlRowType.DataRow)

            {

                e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';";

                e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";

                string jsCommand = string.Format("if ({2} != {1}) __doPostBack('{0}','Edit${1}')", GridView1.ID, e.Row.RowIndex, GridView1.EditIndex);

             

                foreach (TableCell c in e.Row.Cells)

                {

                    if (c == e.Row.Cells[1])

                    {

                    }

                    else

                    {

                        c.Attributes["onclick"] += jsCommand;

                       

                    }

                }

            }

        }

        catch (Exception ex)

        {

 

        }  

    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

    {

      

    }

    protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)

    {

     

    }

    //This event is used to check the click whether it is single or double click

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

    {

        int selectedIndex = int.Parse(e.CommandArgument.ToString());

        string _commandName = e.CommandName;

        switch (_commandName)

        {

            case ("SingleClick"):

                {

                   

                    GridView1.SelectedIndex = selectedIndex;

                    object send = new object();

                    GridViewEditEventArgs ex = new GridViewEditEventArgs(selectedIndex);

                  

                   GridView1_RowEditing(send, ex);

                   

                    break;

                }

        }

    }

    //this event is used to change the background color of row if user mouseover the row.

    protected void GridView1_DataBound(object sender, EventArgs e)

    {

        foreach (GridViewRow row in GridView1.Rows)

        {

            if (row.RowType == DataControlRowType.DataRow)

            {

                // Add javascript to highlight row

                row.Attributes["onmouseover"] =

                   "javascript:NAC_ChangeBackColor(this, true, '#BAD5E8'); this.style.cursor = 'hand';";

                row.Attributes["onmouseout"] = "javascript:NAC_ChangeBackColor(this, false, '');";

               

               

                foreach (Control c in row.Cells[0].Controls)

                {

                    if (c is LinkButton)

                    {

                        LinkButton selectButton = (LinkButton)c;

 

                        // Get the javascript which is assigned to this LinkButton

                        String jsClick = ClientScript.GetPostBackClientHyperlink(selectButton, "");

 

                        // Get command name in lowercase

                        String commandName = selectButton.CommandName.ToLower();

 

                        // Add this javascript to the onclick Attribute of the row

                        if (commandName == "details")

                            row.Attributes["onclick"] = "NAC_StartSingleClick(\"" + jsClick + "\");";

 

                        // Add this javascript to the ondblclick Attribute of the row

                        if (commandName == "edit")

                            row.Attributes["ondblclick"] = "NAC_StartDblClick(\"" + jsClick + "\");";

 

                        // set the link button to be invisible

                        if (commandName == "details" || commandName == "edit")

                            selectButton.Visible = false;

                    }

                }

            }

        }

    }

    //this is the preRender event used to render the control from client side to server side

    protected void GridView1_PreRender(object sender, EventArgs e)

    {

 

    }

}