Creating a New Row in a Grid Using Javascript

I'm encountering an issue with my Grid View and JavaScript code. When I click the button to add a new row, it successfully adds the row but carries over the data from the previous row and fails to save to the database, resulting in an "Invalid Number" error.

<script type='text/javascript' language='javascript'>
    function AddNewRecord() {
        var grd = document.getElementById('GridView1');
        var tbod=grd.rows[0].parentNode;
        var newRow=grd.rows[grd.rows.length - 1].cloneNode(true);
        tbod.appendChild(newRow);
        return false;
    }
</script>

<asp:Button ID="Button2" runat="server" Text="Add Row" OnClientClick="return AddNewRecord();"/>

How can I ensure that each new row is generated empty and can be saved to the database?

Here's the code for the Grid:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" OnRowCreated="myGridView_ItemCreated" Headerstyle-CssClass="myStyle"
    BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4" Width="859px">
    <RowStyle BackColor="White" ForeColor="#003399" HorizontalAlign="Right" />
    <Columns>
        <!-- Columns Content Here -->
    </Columns>
    <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
    <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
    <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
    <HeaderStyle BackColor="CornflowerBlue" Font-Bold="False" ForeColor="White" Font-Names="Arial" Font-Size="9pt" CssClass="myStyle" />
</asp:GridView>

Answer №1

When using cloneNode(true), the new row will contain the same data as the previous row. To make it empty, you can use .text("") on each element within the row. Without seeing the HTML structure, I cannot provide specific code examples.

Answer №2

In your specific situation, you are using JavaScript to create a new row in a gridview that is not recognized as a server-side control. Therefore, when a postback occurs, the state of the control cannot be saved in the viewstate. This is why you are unable to save the data to the database.

My suggestion is to add an asp:hidden field on the page where you can store the data from the new row (all columns). When you click a button, it will trigger a postback event. You can retrieve the data of the new row by accessing the value of this hidden field and then proceed to save it to the database.

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

What causes Child component to re-render in this basic example of React?

After devouring countless articles on React renders and composition, I found myself in a sea of conflicting information. However, I remember a key point that stood out to me: if React still has the same children prop it received from the App last time, it ...

What is the best way to retrieve a value from $http or $resource using this filter?

Within my HTML, I have a structure that looks like {{ i.userId | userName }}. Essentially, I am attempting to convert this into a name by utilizing a filter. However, I am encountering numerous challenges with the asynchronous function required to retrieve ...

Adjust the variable's value

After clicking on the "Add to Cart" button, the value is added to ".total-cart". When an option is selected in , its value is also added to the total cart value and displayed in ".total-all". However, clicking "Add to Cart" again does not update the value ...

Having Difficulty Formatting HTML Input in Next.js

I'm encountering difficulties when trying to style HTML form elements in Next.js. I've been unsuccessful in applying CSS using a simple class name from the imported stylesheet, but have managed to achieve some success with inline styling by using ...

Obtaining the current page's URL

I am trying to determine if a particular string is present in the current URL of the page. I am aware that this can be done using ClientQueryString.Contains. However, the challenge I am facing is that the page I need to make changes to already inherits Sys ...

Ajax request yields an empty result

I have a very basic HTML page that includes some PHP and jQuery functionality <script type="text/javascript"> $(document).ready(function() { $.ajax({ url: "test.php", type: "POST", ...

Encountering an error in Strapi project: URL undefined

I am currently in the process of setting up a Strapi application and getting it up and running. Following the instructions provided in this document: After successfully setting up Strapi and creating the application, I encountered an error when trying to ...

How to modify attributes using ng-content in Angular 2

Looking for a way to modify the attribute of the top div within the ng-content in my code. Here's an example snippet: <ng-container> <ng-content select="[content-body]"></ng-content> </ng-container> For instance, I want t ...

A simple guide to running Express Js and MongoDB from the command line and gracefully closing the terminal

Is there a way to run an Express project without the terminal being visible or easily closed? I need my server to stay running, but I don't want the user on the local PC to be able to see or close the terminal. Any suggestions on how to achieve this ...

What is the best way to refresh the content of an iframe when a link within the iframe is clicked?

In the code below, I am resizing the iframe based on its content: <html> <head> <title></title> </head> <body> <iframe src="http://page.html" id="iframeid" width="600" height="700" scrolling="n ...

Sending a Form Generated in Real Time with a Button Located Outside the Form

I'm currently working on a feature that allows users to add multiple invoices on a single page. Users can click on a link to display the invoice fields in a modal form, which is dynamically generated using AJAX. Once the user has filled out the requi ...

Explore the AngularJS ui-routing project by visiting the website: https://angular-ui.github.io/ui-router/#resources

I am currently working on creating a sample app using AngularJS ui-routing. There is a tutorial that I am following which can be found here When I try to run the site locally in Chrome, I am encountering some errors in the console. Below are the errors tha ...

Is it possible to have Vue.js code within a v-for loop in such a way that it executes every time the v-for loop runs?

<div class="questions" v-for="(q,index) in questions " :key="index" {{this.idx+=1}} > <h3 > {{q.content}}</h3> <h3> A) {{q.a}} </h3> <h3> B) {q.b}} </h3> ...

Tips on saving all objects, even those that are repeated, in a JavaScript array

My goal is to store and display all objects, even if they are repeated, but the current setup only allows for storing unique values. The positive aspect is that it calculates the total by summing up all values, including duplicates. The Negative aspect is ...

Exposing a factory JS variable globally within an AngularJS environment

I am trying to access a variable created within a factory in another function in my AngularJS controllers. How can I achieve this and make the new calculated value available? The variable I want to use is result.data.bkor_payamount = result.data.bkor_paya ...

Perform an asynchronous reload of DataTables using ajax.reload() before calling a function

I need help extracting real-time data from a datatable and populating a form for editing when an edit button is clicked on each row. Despite my efforts, the ajax.reload() function doesn't load the table in time to fill the form with correct data. The ...

Endless Loop Encountered When Attempting to Split a Vuex Array

If you want to check out my codesandbox setup, you can find it here. In this setup, three dates should be printed. The important parts of the code are as follows: import Vue from "vue"; import App from "./App"; import Vuex from "vuex"; Vue.use(Vuex); co ...

Creating a seamless fusion of GenericHtmlControl/Literal with an Asp.net Control through dynamic rendering

My Environment is: ASP.NET 4.62 / C# / Boostrap 4 framework My application dynamically generates a bootstrap 4 menu from a database query. I have a div in the aspx page <div id="myNav" runat="server"></div> and I add code ...

Tips for concealing images within a designated list and revealing them in a separate list

I have a question regarding image visibility. Is it possible to hide certain images from a "SHOW ALL" list, but have them appear in a different category list? Below is the code snippet: <section> <ul class="portfolio_filters"> < ...

Using identical variable names for functions in Node.js

I'm feeling a bit puzzled about the following code snippet. Is it possible to create a class in JavaScript like this? module.exports = function testName(params){ testName.test = function(req, res){ //some code here } return testName; } Inste ...