A guide to activating double and single click functionality for GridView rows in Asp.net using C#

I have a GridView row in Asp.net and currently have a single click event working on it. However, I now require a Double Click event for my Grid rows. Can anyone provide guidance on how to achieve this?

Your assistance is greatly appreciated.

Answer №2

        public void HandleGridViewRowDataBound(object sender, GridViewRowEventArgs e)
                {
                    if (e.Row.RowType == DataControlRowType.DataRow)
                    {
                        // Accessing the LinkButton control in the first cell
                        LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
                        // Obtaining the assigned javascript for this LinkButton

          string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");
                        // Adding a delay of 300 milliseconds to prevent immediate postback on first click
                        _jsSingle = _jsSingle.Insert(11, "setTimeout(\"");
                        _jsSingle += "\", 300)";
                        // Attaching this javascript to the onclick Attribute of the row
                        e.Row.Attributes["onclick"] = _jsSingle;

                        // Accessing the LinkButton control in the second cell
                        LinkButton _doubleClickButton = (LinkButton)e.Row.Cells[1].Controls[0];
                        // Obtaining the assigned javascript for this LinkButton
                        string _jsDouble = ClientScript.GetPostBackClientHyperlink(_doubleClickButton, "");
                        // Attaching this javascript to the ondblclick Attribute of the row
                        e.Row.Attributes["ondblclick"] = _jsDouble;
                    }
                }



                public void HandleGridViewRowCommand(object sender, GridViewCommandEventArgs e)
                {
                    GridView _gridView = (GridView)sender;

                    // Retrieving the selected index and the command name
                    int _selectedIndex = int.Parse(e.CommandArgument.ToString());
                    string _commandName = e.CommandName;

                    switch (_commandName)
                    {
                        case ("SingleClick"):
                            _gridView.SelectedIndex = _selectedIndex;
                            this.Message.Text += "Single clicked GridView row at index " + _selectedIndex.ToString() + "<br />";
                            break;
                        case ("DoubleClick"):
                            Response.Write("<script type='text/javascript'>detailedresults=window.open('Patient//PatientDicomViewPage.aspx');</script>");

                            // Response.Redirect("ViewPatient.aspx");
                            this.Message.Text += "Double clicked GridView row at index " + _selectedIndex.ToString() + "<br />";
                            break;
                    }
                }


    Grid Design

     <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#DEDFDE" 
                BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" 
                OnRowDataBound="HandleGridViewRowDataBound" OnRowCommand="HandleGridViewRowCommand">
                <FooterStyle BackColor="#CCCC99" />
                <Columns>                
                    <asp:ButtonField Text="SingleClick" CommandName="SingleClick" Visible="false"/>
                    <asp:ButtonField Text="DoubleClick" CommandName="DoubleClick" Visible="false"/>
                </Columns>
                <RowStyle BackColor="#F7F7DE" />
                <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
                <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />            
                <AlternatingRowStyle BackColor="White" />
            </asp:GridView>
<asp:Label id="Message" runat="server" ForeColor="Red" Font-Bold="true"></asp:Label>  

Answer №3

Here is a different approach that focuses on handling double clicks:

For the front end implementation, include the following:

OnRowDataBound="YourGrid_RowDataBound" OnRowEditing="YourGrid_RowEditing" 

On the backend side:

protected void YourGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["ondblclick"] = Page.ClientScript.GetPostBackClientHyperlink(YourGrid, "Edit$" + e.Row.RowIndex);           
            e.Row.Attributes["style"] = "cursor:pointer";
        }
    }
    
    protected void YourGrid_RowEditing(object sender, GridViewEditEventArgs e)
    {
        // Your custom code goes here
        // For example:
        // Access the grid
        GridView grid = (GridView)sender;
        // Access the edited row
        GridViewRow editedRow = (GridViewRow)grid.Rows[e.NewEditIndex];
        // Retrieve data from a specific cell in the row
        string cellData = editedRow.Cells[1].Text.ToString();
        
       
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Program does not display the expected alert message when using if/else statement

I'm grappling with creating a basic program that accomplishes the following: Develop a function declaration named changePowerTotal which accepts: The total current power generated (a numeric value) A generator ID (a number) The new status of ...

Issue: Unable to extract the 'title' property from '(0 , react__WEBPACK_IMPORTED_MODULE_1__.useContext)(...)' as it is not defined (Next.js Chat App)

Currently facing an issue with the error message "Cannot destructure property 'title' of '(0 , react__WEBPACK_IMPORTED_MODULE_1__.useContext)(...)' as it is undefined" while developing a chat application using Next.js and Solidity. Desp ...

Is it not possible to use GLOB with JSHint on Windows operating systems?

Currently, I am experimenting with using NPM as a build tool (). My experience with NPM is limited, and at the moment I only have JSHint and Mocha installed. Attached is my package.json file. However, when I try to run "npm run lint" in the Windows 7 comma ...

Implement a new list field to an object using javascript

I am facing a challenge in converting a JSON object to a list of JSON objects and then adding it back to JSON. Here is an example: config = { existing_value: 'sample' } addToListing = (field, value, index=0) => { config = { ...confi ...

Navigating through different components within a single page

Each segment of my webpage is a distinct component, arranged consecutively while scrolling e.g.: <sectionA></sectionA> <sectionB></sectionB> <sectionC></sectionC> All the examples I've come across involve creating ...

Switching effortlessly between Fixed and Relative positioning

As I work on creating a unique scrolling experience, I aim to have elements stop at specific points and animate before returning to normal scroll behavior once the user reaches the final point of the page. Essentially, when div X reaches the middle of the ...

AngularJS encountered an error following a successful GET request

I'm attempting to retrieve data from the server using this code snippet. $scope.get_file_list = function() { delete $http.defaults.headers.common['X-Requested-With']; //We don't want OPTIONS but GET request $htt ...

Can anyone provide guidance on how to trigger 3 unique functions in a specific order using JavaScript?

I've been troubleshooting this issue for quite some time, but I just can't seem to figure it out. Here's my dilemma: I have three functions - one to shrink a div, one to reload the div with new data, and one to enlarge the div - all triggere ...

Tips on preventing repeated data fetching logic in Next.js App Routes

I'm currently developing a project with Next.js 13's latest App Routes feature and I'm trying to figure out how to prevent repeating data fetching logic in my metadata generation function and the actual page component. /[slug]/page.tsx expo ...

Incorporating HTML5 Video Using an AJAX Request

I am attempting to fetch a video using an ajax query, but it seems that the video player control buttons are missing. Here is the code I am using: $.ajax({ context: document.body, url: "/?get=json&act=video", type: "get", success: fu ...

What is the best way to store the JSON data that is returned in a JavaScript function as a variable

My goal is to save the client's IP address in a variable after fetching it in JSON format from api.ipify.org. I have managed to display the IP if I alert the result, but I am struggling to store it in a variable. This code snippet works: <script& ...

'Without the need to refresh the page, assign a JavaScript variable from JSP on the server side.'

I'm looking for a way to assign a JavaScript variable from JSP without triggering a full page reload. While my current code successfully sets the variable, it also causes the entire page to refresh as a side effect. Here's an example in the exam ...

Tips for closing the stdio pipes of child processes in node.js?

Looking to spawn a child process from node.js and monitor its stdout before closing the pipe to terminate the node process. Here's my base code snippet that is currently not ending the node process: const childProcess = require("child_process"); con ...

Dealing with undefined Ajax values in PHP

Every time I call the function, I receive an undefined value and it's baffling me as to what could be causing this issue. You are logged in as undefined, Error undefined Ajax script: function Submit() { console.log('asd') $.ajax({ ...

Query the ASP.NET application for variables whose names begin with "xxx."

I am in the process of developing a turn-based game site using ASP.NET. Players have the option to either create a new game or join an existing one. To keep track of each game, I plan to create application-level variables with a specific prefix, such as " ...

developing a selenium grid by generating nodes through code

I'm currently working on developing a Java application that can initiate a node and connect it to the hub. I've successfully achieved this when both the hub and node are located on the same computer. However, when attempting to connect to a diffe ...

How can I implement a division animation with Javascript upon clicking a hyperlink?

I need help with animating a div when clicking on a link. Specifically, when clicking on the "About" link, the height of the div should change. Currently, the height is set to '0em' in the CSS file. I attempted to change the height using "documen ...

Tips for preserving the status of radio buttons in a React application

I am currently utilizing a Map to keep track of the state of radio buttons, but I am facing challenges when it comes to correctly saving and updating it whenever a user makes a selection. The structure of my Map is as follows: { "Group A": [ ...

Add elements to an array following an AJAX request

On my .cshtml page, I have the following script: $(function () { var tempArray = []; var tbValue = $('#tb1').val(); $.ajax({ url: "/ControllerName/getdata", dataType: 'json', ...

Removing a Dynamic Element in ReactJS

--CustomFieldSection.js-- import React, { Component } from 'react'; import CustomField from './CustomField.js'; class CustomFieldSection extends Component{ constructor(props){ super(props); this.stat ...