Retrieving dynamically created row from code-behind

My ASPX page contains a table with headings. I am dynamically adding rows to the table using JavaScript, but when trying to access these newly added rows on the server side, I can only see the heading row and not the new ones. The table always appears to have only one row, and I am unable to access the dynamically added rows.

ASPX page

<table runat="server" id="tblNew" clientidmode="Static">
                                        <tr>
                                            <th>
                                                Column1
                                            </th>
                                            <th>
                                                Column2
                                            </th>
                                        </tr>
                                    </table>

Javascript function for adding rows.

    var table = document.getElementById("SelectedItems");
    var newrow = table.insertRow(0);
    var newcel0 = newrow.insertCell(0);
    var newcel1 = newrow.insertCell(1);

CS TO access table rows

    int rowCount=tblNew.Rows.Count;

Despite my efforts, I consistently receive a count value of one. Any help would be greatly appreciated.

Answer №1

While your JavaScript runs in the browser, your CS code is executed on the server. The server code is processed before the generated HTML page is sent to the web browser.

To address the issue, consider inserting rows into the table using CS code rather than JavaScript. This approach should resolve the problem at hand.

Answer №2

If you're looking for a way to keep track of counts in your table, I recommend using a hidden field like this:

<input type="hidden" value="0" runat="server" id="hiddenRowCount"/>

When adding new rows to the table with JavaScript, make sure to increment the count accordingly:

var table = document.getElementById("<%=tblNew.ClientID%>");
var newrow = table.insertRow(0);
newrow.insertCell(0);
newrow.insertCell(1);

// Retrieve current hidden field value
var rowCount = document.getElementById('<%=hiddenRowCount.ClientID%>').value;

if (rowCount != '') {
    rowCount = parseInt(rowCount) + 1;
} else {
    rowCount = 1;
}

document.getElementById('<%=hiddenRowCount.ClientID%>').value = rowCount;

To calculate the total number of rows on the server side, use this code snippet:

int totalRows = this.tblNew.Rows.Count + Convert.ToInt32(this.hiddenRowCount.Value);

Tip: If you need to dynamically remove rows with JavaScript, remember to update the counter accordingly.

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

I'm looking for a simple method to create both a dark mode and light mode for an HTML page using Javascript. Can anyone help me out with

Struggling to create a website and stuck on implementing a dark/light theme using JavaScript. Any suggestions on an easier way to accomplish this? I was thinking of selecting elements with specific styles and adjusting the CSS color property. Initially a ...

Tips for globally overriding MUIv4 class in JSS for nested themes

Summary: Skip to EDIT2 MUIv4 has generated the following classes for me based on my nested theming: <label class="MuiFormLabel-root-121 MuiInputLabel-root-113 MuiInputLabel-formControl-115 MuiInputLabel-animated-118 MuiInputLabel-shrink-117 M ...

What causes the content of my container to disappear following a setInterval div swap in Internet Explorer?

While developing a website on Chrome and Firefox, I was informed that it also needs to function properly in Internet Explorer. I managed to resolve the double padding issue in IE, but now I'm facing a new problem. The content of my "grid" disappears a ...

When examining the buffer property of each uploaded file, particularly when dealing with multiple files

I'm encountering an issue while trying to upload multiple files to my server using multer. Although I can access the req.files array, I am unable to retrieve the buffer property of the files. Upon attempting to log them with console.log, all I get is ...

Converting JSON to CSV using JavaScript

While utilizing this script (which is functioning properly), I encountered an issue where I needed to exclude certain columns (specifically columns 1, 2, 3, and 9) from the extraction process. Here's what I've got so far: $(document).ready(funct ...

Struggling to make JavaScript read JSON data from an HTML file

I am currently working on developing a word search game using django. One of the tasks I need to accomplish is checking whether the entered word exists in a dictionary. To achieve this, I have been converting a python dictionary into JSON format with json. ...

Looking for guidance on configuring an email composer in a PhoneGap application

Seeking assistance in troubleshooting the email composer plugin for my PhoneGap app (using JQueryMobile). In my config.xml, I have included the plugin as shown below; <plugin name="cordova-plugin-email-composer" spec="https://github.com/katzer/cordova ...

Error: The term 'RequestCompleted' is not recognized by Microsoft JScript

Does anyone have any suggestions? The error above occurs when this code is executed: Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RequestCompleted); Specifically within this section: <script language="javascript" type="text/javas ...

transferring data between PHP frames

Having a PHP variable within a frame from a frameset that must be passed to two other frames at the same time is proving to be a challenge. One of those frames refreshes every 5 seconds, making it easy to extract the variable from the URL. The other frame, ...

What steps can be taken to prompt the layout to transition?

I have an element that sticks to the top based on the current scroll offset. The issue is that the layout doesn't update when there is space available after the stuck element. This creates a ghost gap where the stuck element used to be... http://fidd ...

How to efficiently traverse an array in C# by making use of multiple iterations

We have a unique application that requires the deserialization of data from a single stream into various objects. The Data array contains multiple messages packed together, each with variable length and no specific delimiting codes in the stream. Our goa ...

Configuring environment variables during Jest execution

A variable is defined in my `main.ts` file like this: const mockMode = process.env.MOCK_MODE; When I create a test and set the variable to true, it doesn't reflect as `'true'` in the main file, but as `'false'` instead. describe ...

React counter variable failing to increment

I have 6 cubes displayed on the screen along with a counter. Whenever a cube is clicked, its background color changes to red and the counter increments by one. However, I'm facing an issue where the counter remains at 1 even after clicking on multiple ...

Can you explain the functionality of templates in the Primeng grid for Angular 6?

In my project, I am incorporating the use of primeng TurboTable which utilizes a pTemplate directive for templates. I am attempting to replicate this approach in order to create a reusable (DUMB) component. Despite my efforts to find a solution, I have not ...

Create a simple three-sided shape using Three.js

Currently, I am working on familiarizing myself with three.js in order to create a basic triangle. However, despite my efforts, the code I have written does not seem to be functioning properly. var scene = new THREE.Scene(); var camera = new THREE.Perspec ...

Svelte's feature prevents users from inputting on Mapbox

My goal is to prevent user input when the variable cssDisableUserInput is set to true. Here's what I have within my main tags: <div id=userinput disabled={cssDisableUserInput}> <div id="map"> </div> Within my CSS, I&a ...

Unlimited Cycle using Vue Router Global Precautionary Measures

Currently, I am facing an issue with redirecting users using Firebase Auth and Vue Router. The problem arises when the Router redirects the user to '/' as it results in a blank white screen on the website. I am aware that there is an error in m ...

Deployment of multiple versions in Azure Web Sites is a breeze

Our company works with multiple clients who use Azure web sites to host our web application. Currently, when we upgrade a client to a newer version of our software, we have to upgrade all clients to the latest version simultaneously. However, we are looki ...

Is there a way to determine which 'a href' link was selected on the previous webpage?

Being relatively new here, I have often visited Stack Overflow to find answers to questions that I have, only to discover that most of them have already been asked before (heh). However, I am facing a dilemma now. I have a homepage with two div elements ...

Unexpected unusual occurrences

Regarding an issue with ASP.NET MVC and LINQ, I am encountering 2 exceptions randomly upon reloading the page between 8-12 times. The nature of the exceptions is also random - it could be one or the other. Here are the details of the exceptions: [IndexOut ...