Only include the Edit button in the asp:GridView and eliminate the Update and Cancel buttons

Working with the asp:GridView can be a bit tricky sometimes. The Edit hyperlink automatically added to each column poses a challenge if you want to customize the editing experience beyond what the GridView offers. Ideally, I would like to click the Edit hyperlink and have it open a new panel for more extensive edits without encountering the Update and Cancel buttons that typically appear.

I managed to add the desired functionality by creating an event handler that deals with GridView.RowCommand when the command name is "Edit". However, attempts at programmatically clicking Cancel or finding other solutions to prevent the appearance of Update and Cancel buttons post-edit have not been successful.

Exploring alternatives such as removing the default Edit button entirely and handling a different event through my event handler seems like a viable option to avoid the limitations posed by the automatic Edit hyperlink. Unfortunately, resources on this topic are scarce, mostly focusing on disabling manually created Edit buttons rather than dealing with the built-in one that I'm struggling to remove.

Answer №1

When you open a panel, it might be a good idea to ditch the entire template and auto-editing system. For quick and simple solutions, the built-in GV events are fantastic for getting started.

Once you understand how everything works, you can code your way through this and end up with less code, markup, and hassle!

You can even get rid of the GV "row" handler since it doesn't offer much help here.

For an even better approach, just add a basic edit button - even an asp.net one will do. You don't need anything more complicated! Adding buttons to the GV gives each button its own click event, similar to any other control or button in the GV.

If you're looking to navigate and edit the GV like Excel, I have a simple solution that doesn't rely on the built-in GV events.

Let's outline how this can work with minimal code.

You haven't specified the type of dialog you're using (there are many options, from jQuery.UI to AjaxToolkit), but I'll go ahead with jQuery.UI for this example.

Our goals:

- Eliminate the messy GV event model
- Use and write easy server-side code whenever possible
- Minimize JavaScript code usage

Now, I'll be using a few helper routines I've written in vb.net. They're short and easy to use, saving me from repeating the same code:

- Moving data between a data table and controls for editing
- Reversing the process above to save changes back to the database

Even without these "move to/from" routines, removing the GV events already simplifies the code significantly.

Let's consider a simple grid of hotels where we want an edit button on each row.

Here's the initial setup for our grid:

<div style="width:40%">
    <asp:GridView ID="GHotels" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="ID" CssClass="table">
        <Columns>
            <asp:BoundField DataField="FirstName" HeaderText="FirstName"  />
            <asp:BoundField DataField="LastName" HeaderText="LastName"  />
            <asp:BoundField DataField="HotelName" HeaderText="HotelName"  />
            <asp:BoundField DataField="Description" HeaderText="Description"  />
            <asp:TemplateField HeaderText="Edit">
                <ItemTemplate>
                    <asp:Button ID="cmdEdit" runat="server" Text="Edit" CssClass="btn" OnClick="cmdEdit_Click" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

Some notes: I used wizards to create the initial setup and then adjusted the datasource settings. The PK row setting is now handled by `DataKeyNames="ID"` for maintaining the ID without exposing it in the markup.

Setting `CssClass="table"` adds Bootstrap styling to the GV, making it look nicer and responsive to div width.

The corresponding code includes:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not IsPostBack Then
        LoadGrid
    End If

End Sub

Sub LoadGrid()

    Dim cmdSQL As New SqlCommand("SELECT * FROM tblHotelsA ORDER BY HotelName")
    GHotels.DataSource = MyrstP(cmdSQL)
    GHotels.DataBind()

End Sub

This results in:

https://i.sstatic.net/9kWxc.png

So far, so good.

For editing purposes, let's assume you're using some kind of popup system. I'll opt for jquery.UI as it works well compared to bootstrap dialogs.

After the GV, we'll set up a one-row editor within a hidden div, like this:

<div id="EditRecord" runat="server" style="float:left;display: none">
    <!-- Editor content goes here -->
</div>

Next, we define the contents of the editor with appropriate form elements such as textboxes, checkboxes, and buttons. Styling ensures a neat presentation.

Finally, we add a simple JavaScript function to handle popping up the editor:

<script>
    function PopEdit() {
        var myDialog = $("#EditRecord");
        myDialog.dialog({
            title: "Edit Hotel Information",
            modal: true,
            width: 860,
            appendTo: "form"
        });
    }
</script>

That wraps up the setup.

Regarding the row button click event, it involves retrieving the row details based on the clicked button and populating the editor with that information:

Protected Sub cmdEdit_Click(sender As Object, e As EventArgs)

    Dim btn As Button = sender
    Dim gRow As GridViewRow = btn.NamingContainer
    Dim pkID = GHotels.DataKeys(gRow.RowIndex).Item("ID")

    ' SQL query to fetch hotel details based on PK ID
    Dim cmdSQL As New SqlCommand("SELECT * from tblHotelsA where ID = @ID")
    cmdSQL.Parameters.Add("@ID", SqlDbType.Int).Value = pkID
    Dim rstData As DataTable = MyrstP(cmdSQL)

    ' Loading the editor with fetched data and displaying it
    Call fLoader(Me.EditRecord, rstData.Rows(0))
    ViewState("rstData") = rstData
    ClientScript.RegisterStartupScript(Page.GetType(), "PopEditKey", "PopEdit()", True)

End Sub

The simplicity lies in loading data into controls and invoking the pop-up dialogue using only one line of jQuery.UI script.

For saving changes back to the database upon clicking the Save button, we have the following server-side code:

Protected Sub cmdSave_ServerClick(sender As Object, e As EventArgs)

    Dim rstData As DataTable = ViewState("rstData")
    Call fWriterW(EditRecord, rstData.Rows(0))
    Call SaveTable(rstData, "tblHotelsA")
    LoadGrid()

End Sub

The Cancel/Back button does not require much code due to the collapse behavior upon postback. Similarly, additional functionality like delete prompts can be implemented utilizing server-side VB code paired with jQuery.UI for a clean interface.

To streamline the process, helper routines like MyRstP, fLoader, fWriterW, and SaveTable simplify interactions with databases, controls, and user input.

By leveraging these routines and avoiding unnecessary complexity, handling data editing in the GridView becomes swift and efficient.

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

Tips for addressing dependency issues in react native applications

Starting a new ReactNative project using "react-native init newProject" is giving me some warnings. How can I resolve these issues? npm WARN deprecated [email protected]: core-js@<2.6.5 is no longer maintained. Please, upgrade to core-js@3 o ...

Using an In-Memory Isolated Neo4J Database to Test NodeJS Applications

Can anyone suggest a method to quickly create small in-memory Neo4J database instances for testing NodeJS code with Jest? ...

JavaScript countdown timers should maintain their progress even after the page is reloaded

I am encountering an issue with a timer on my checkout page. We have a 2-step checkout process, and after completing step 1, the webpage reloads to step 2, causing the timer to restart. I need the timer to continue counting without resetting. Below is the ...

Steps to temporarily turn off Backbone.sync for a fresh model and then reactivate it once the user clicks the save button

I am currently working with a Backbone collection model that consists of sub-models as elements, along with views to edit it. My objective is to have the syncing functionality "turned off" initially when the model is created, so that the back end is not c ...

Close the material-ui popper when clicking away

I am currently working on implementing a Material UI popper feature that should close when the user clicks outside of it using ClickAwayListener. However, I have been unable to make this functionality work despite trying different approaches. I've att ...

Updating an image periodically with React

I'm attempting to create a slideshow that changes images every second. The first image displays, then switches to the alternate display without continuing to switch between pictures. export default class Slideshow extends Component { constructor ...

Determining whether a Typescript AST node represents a javascript native function

How can I determine if an AST node in TypeScript represents a valid JavaScript function, as opposed to a custom method? Here's what I'm thinking: function isJavascriptFunction(node: ts.Node): boolean { // ----- } For instance, given the cod ...

Storing and Editing Collection of Elements

My latest project involves creating a basic web scraping tool that gathers information on apartment prices from a specific webpage. Each time the tool runs, it compiles an array of objects with details such as date, time, floor plan name, bed number, floor ...

Having difficulty integrating a stored procedure into a 3-tier architecture using code-first implementation

I have a project that follows the 3-tier architecture pattern. It includes BLL and DAL .dll files in references. Now, I need to utilize a new Stored Procedure that has already been created in SQL Server Management Studio for this project. I have created a ...

Node - A circular @import reference has been detected

Recently, I've dived into the world of JavaScript, node.js, and related technologies. My goal is to create a front-end development environment from scratch using tools like gulp, bower, browser sync, and various plugins. I've made significant pr ...

The name 'withStyles' is nowhere to be found

import * as React from "react"; import Button from "@material-ui/core/Button"; import * as PropTypes from "prop-types"; import {WithStyles} from '@material-ui/core'; import "./App.css"; import PageTwo from "./components/PageTwo"; ...

The art of aligning text in CKEditor5

I am attempting to configure my page using the CK5 editor. So far, I have done the following: ClassicEditor.create(document.querySelector('#editor'), { language: 'pt-br', toolbar: ['heading', '|', 'bold&apo ...

Discover the greatest values housed in every individual subarray

I'm attempting to extract the largest value from each subarray and store those values in a new array, but for some reason, the output is always an empty array. I can't seem to figure out what's wrong with my code. function findLargestValu ...

Execute JavaScript function once instead of repeatedly

I am seeking a JavaScript code that can verify the size of an input file before uploading whenever the user changes the input value (i.e. whenever a file is selected for upload). Here is what I have come up with so far: var file = document.getElementById ...

Swapping out an entire item in a designated array index for a different object

I am faced with a JavaScript object conundrum: const myValidation = [ { id:'1', name:'qqq', field1: 'Yes', field2: 'No', field3: 'Yes' }, { id:'330', name:'www', ...

What are the capabilities of Ajax when it comes to utilizing select controls in J

Is there a way to trigger an ajax call when a select control value is clicked? The onChange event doesn't seem to work for me in this case :( This is what I have tried so far: JAVASCRIPT: <script> function swapContent(cv) { $("#myDiv"). ...

The WYSIWYG niceEdit editor is incompatible with textareas generated through ajax-php calls, causing it to malfunction

My AJAX-generated textarea is not converting into a WYSIWYG Editor once loaded. The normal textarea works fine, but I need assistance in solving this issue. <!DOCTYPE html> <html> <head> ........ $.ajax({ type: "POST", ...

The media query does not apply to other pages because they are not responsive

Currently experiencing an issue with fullpage.js on my single page website. The home page fits perfectly within the viewport, but for subsequent pages, the bottom portion is not visible on the same media query. ...

An element in AngularJS is replicated for a brief moment of 1 second

I am having trouble with my login form that displays an error message in a box. <div class="ui negative message" ng-if="vm.message != ''"> <span ng-bind="vm.message"></span> </div> The error message is being set in t ...

Mouseover feature for image is functioning, but having issues with alignment

I am currently working on displaying images upon mouse over actions. While the functionality is working perfectly, I am facing an issue where the displayed images appear below and the last image takes up space at the bottom. To rectify this problem, I woul ...