Attempting to activate an ASP button that is created within a gridview after pressing the enter key within a textbox

I am currently working on a gridview with dynamically generated rows, each row containing text boxes and buttons. The goal is to update the database with values from the textboxes when UpdateBtn1 is clicked. Users should be able to either click the button or hit enter while editing the textboxes to trigger the update.

Here is my current progress:

<asp:GridView ID="InitialData" runat="server"
                AutoGenerateColumns="False"
                OnRowDataBound="gv_GridDataBound"
                OnRowCommand="InitialRowButton_Click"
                DataKeyNames="ID" OnSelectedIndexChanged="InitialData_SelectedIndexChanged">
                <Columns>
                    <asp:TemplateField HeaderText="Update">
                        <ItemTemplate>
                            <asp:Button ID="UpdateBtn1" ButtonType="Button" Text="Update" runat="server"
                                CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" CommandName="Run_Update" />
                        </ItemTemplate>
                    </asp:TemplateField>

                    <asp:BoundField ReadOnly="true" HeaderText="Data" DataField="Data" />
                    <asp:BoundField ReadOnly="true" HeaderText="Data" DataField="Data" />
                    <asp:BoundField ReadOnly="true" HeaderText="Data" DataField="Data" />
                    <asp:BoundField ReadOnly="true" HeaderText="Data" DataField="Data" />
                    <asp:BoundField ReadOnly="true" HeaderText="Data" DataField="Data" />

                    <asp:TemplateField HeaderText="Input Textbox1">
                        <ItemTemplate>
                            <asp:Button ID="RequestBtn" CommandName="Get_Weight" HeaderText="Request Weight"
                                CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" runat="server" Text="Request Weight" />
                            <asp:TextBox ID="InputText1" runat="server" Text='<%# Eval("MEASURED_WEIGHT") %>' Width="50px" />
                            <asp:RegularExpressionValidator ID="RegularExpWeightBox"
                                ControlToValidate="InputText1" runat="server" ErrorMessage="Illegal"
                                ValidationExpression="^[0-9]{0,5}$" class="regExpress">
                            </asp:RegularExpressionValidator>
                        </ItemTemplate>
                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Status">
                        <ItemTemplate>
                            <asp:DropDownList ID="STATUSDDL" AppendDataBoundItems="True" runat="server">
                            </asp:DropDownList>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Input Textbox2">
                        <ItemTemplate>
                            <asp:TextBox ID="InputTextbox2" runat="server" TextMode="MultiLine" Width="200" Rows="2" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

I have tried using the onclick event to trigger the button or a JavaScript function, but I couldn't target the correct row's button. Any assistance would be highly appreciated.

Answer №1

After much consideration, I have found a clever solution to my problem.

To tackle the issue, I decided to enhance the ondatabound method by introducing a new attribute that would trigger a JavaScript function. By extracting the button Id through identifying the control for each and passing it as an attribute, I was able to achieve the desired outcome. Here is the revised C# code:

protected void gv_GridDataBound(object sender, GridViewRowEventArgs e)
{
    Button b_l_updateButton = (Button)e.Row.FindControl("UpdateBtn1");
    e.Row.Attributes.Add("onkeydown", String.Format("RunUpdate(event,'{0}');", b_l_updateButton.ClientID));
}

Below is the updated JavaScript function:

function RunUpdate(e, UpdateButtonID) {
        var keynum

        if (window.event) 
        {
            keynum = e.keyCode
        }
        else if (e.which) 
        {
            keynum = e.which
        }
        if (keynum == 13) {
            document.getElementById(UpdateButtonID).click();
        }
    }    

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

Is it illegal to escape quotes when using an image source attribute and onerror event in HTML: `<img src="x" onerror="alert("hello")" />`?

Experimenting with escape characters has been a fascinating experience for me. <img src="x" onerror=alert('hello'); /> <img src="x" onerror="alert(\"hello\")" /> The second code snippet triggers an illegal character error ...

Tips for deactivating data monitoring in a Vue.js component attribute

Looking to develop a Vue.js component that accepts properties from its parent component, like this example: <table-cell :value="foo" format="date" /> Although value and format are set as properties, Vue automatically sets up obse ...

In ASP.NET, it is possible to only select a single checkbox at a time within a row in a GridView

I have a project where checkboxes are generated dynamically at runtime. I want users to be able to select only one checkbox at a time in each row. Here is my Gridview: <cc1:Grid ID="GrdWorkingCompany" runat="server" OnRowDataBound="GrdWorkingCompany_Ro ...

I would like for this message to appear periodically following the initial execution

I have developed a unique welcome feature using HTML and CSS that I would like to showcase intermittently. --------------------------- My Desired Outcome --------------------------- Initially, this feature should be triggered once (when a user first acce ...

VueJS 3 - Issue with applying the <router-link-active> class to routes that share the same path starting name

In my navigation bar, I have created 3 links which are all declared at the root level of the router object. I've applied some simple styling to highlight the active link on the navbar using the <router-link-active> class. Everything works as exp ...

Focusing in on a PARTICULAR SECTION of the picture

My website has a unique concept - comparing two articles side by side. One of the articles is mine, while the other is displayed alongside it. To capture entire pages for comparison, I utilize Google's GoFullPage feature to take screenshots. The goa ...

Incorporate CSS styling from a separate .css file into a material component

Just starting out with material UI. I have a css file that looks like this: .bgItem { font-size: 14px; } My component setup is as follows: <MenuItem key={status.Id} value={status.Value} classes={css.bgItem}> {status.Description} </Men ...

Using window.location.replace() for redirection after AJAX call succeeds

Attempting to redirect the page after a successful ajax call, the code below is functional: $.ajax( { type: "POST", url: path, data: response1, contentType: "application/json", success: -> window.lo ...

Tips on maintaining the content of an element within a directive template

I'm currently facing an issue with adding the ng-click directive to a button. Here's my HTML: <button class="btn">clicky</button> This is the directive I am using: angular.module('app').directive('btn', function ...

Experiencing unexpected outcomes via AJAX requests

Linked to: Query Database with Javascript and PHP This inquiry is connected to my previous question. I made adjustments to the PHP script based on one of the responses I received; however, when attempting to utilize $.getJSON, I encountered difficulties. ...

Is there a way to retrieve a string with a specific number of empty spaces included?

When working in a different programming language, I utilized the function SPACE(10) to generate a string of 10 spaces. Now, I need to translate this into C#.NET. I attempted using string.Empty().PadLeft(10). Would this be the correct approach? ...

Exploring the Canvas with Full Element Panning, Minimap Included

Currently, I am working on incorporating a mini map onto my canvas that mirrors what is displayed on the main canvas. The main canvas includes zoom and pan functions. I have created a rectangular shape for the minimap to display the content of the canvas. ...

React displaying an error indicating that the setTimeout function is undefined?

While attempting to integrate the XTK library with React, I encountered an issue where it kept throwing an error stating that the setTimeout function is not a valid function. Surprisingly, my code appears to be flawless and works perfectly fine when used d ...

The usage of arrow functions in ReactJS programming

I'm working on a React component that has the following structure: import React, { PropTypes, Component } from 'react'; import { Accordion, Panel, PanelGroup, Table } from 'react-bootstrap'; const FormCell = ({ data }) => ( ...

Duplicating labels with JavaScript

I need assistance with copying HTML to my clipboard. The issue I am encountering is that when I try to copy the button inside the tagHolder, it ends up copying <span style="font-family: Arial; font-size: 13.3333px; text-align: center; background-color: ...

"Enhance user experience with AJAX for selecting multiple checkboxes or performing mult

Hey there! So, I've got a question about handling multiple checkboxes with the same name in a form. Here's an example of what I'm working with: <input type="checkbox" name="myname[]" value="1" /> <input type="checkbox" name="myname ...

Utilizing the useState hook to manage state

Is there a way to fetch the useState from another file in order to export sliderCount? Your assistance is greatly appreciated. I have two files. The first file utilizes the useState function and modifies the state upon button click. In the second file, I ...

Framework7 initialization not triggering when page is initialized

Unable to get init function working in my Framework 7 app. I have attempted all the solutions provided in the following link: Framework7 Page Init Event Not Firing // Setting up Application var myApp = new Framework7({ animateNavBackIcon: true, ...

Are there any solutions for the malfunctioning v8 date parser?

The V8 Date parsing functionality is not functioning properly: > new Date('asd qw 101') Sat Jan 01 101 00:00:00 GMT+0100 (CET) I have attempted to use a delicate regular expression like the following: \d{1,2} (jan|feb|mar|may|jun|jul|a ...

jQuery class toggle malfunction

I have a series of list items with specific behavior when clicked: Clicking a list item will select it and add the class .selected If another list item is clicked, the previously selected item becomes unselected while the new one becomes selected If a se ...