What is the best way to retrieve the value of a cell in the parent gridview while navigating through the child gridview?

I am facing an issue with a JavaScript function that is used to expand and collapse a child gridview inside its parent gridview. My problem arises when I try to retrieve the value of a specific cell in the current row of the parent gridview, or even just its row index. Despite my efforts, I have been unsuccessful in getting the desired result, as I keep retrieving the value or row index of the current row in the child gridview.

Below is the snippet of my aspx code with the JavaScript function:

<script language="javascript" type="text/javascript">
        function toggleDiv(divname)
        {                        
            var div = document.getElementById(divname);
            var img = document.getElementById('img' + divname);
            if (div.style.display == "none")
            {
                div.style.display = "inline";
                img.src = "minus.gif";             
            }
            else
            {
                div.style.display = "none";
                img.src = "plus.gif";          
            }
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>

          <div>
            <input id="Hidden1" type="hidden" runat="server" value="" />

            <asp:GridView ID="gvOrders" runat="server" DataKeyNames="OrderID" Width="750px" AutoGenerateColumns="False" OnRowDataBound="gvOrders_RowDataBound" GridLines="None"
                BorderStyle="Solid" BorderWidth="3px" BorderColor="Blue" style="z-index: 100; left: 126px; position: absolute; top: 96px" BackColor="White" OnRowCommand="gvOrders_RowCommand"
                OnSelectedIndexChanged="gvOrders_SelectedIndexChanged">
            <RowStyle BackColor="#E1E1E1" />
            <AlternatingRowStyle BackColor="White" />
            <HeaderStyle BackColor="LightBlue" Font-Bold="True" ForeColor="Black" />
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <a href="JavaScript:toggleDiv('div<%# Eval("OrderID") %>');">
                            <img id="imgdiv<%# Eval("OrderID") %>" width="9px" src="plus.gif" alt =""/>
                        </a>
                    </ItemTemplate>
                    <ItemStyle Width="20px" />
                    <ControlStyle BackColor="Black" />
                </asp:TemplateField>  
                // Rest of the GridView code

In my code behind, I have the following function:

protected void gvChildGrid_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView gv = (GridView)gvOrders.Rows[e.NewEditIndex].FindControl("gvChildGrid");

            GridViewRow parentRow = (GridViewRow)gv.Parent.Parent;

            int indexRow = int.Parse(parentRow.RowIndex.ToString().Trim()); //gvOrders.Rows[e.NewEditIndex].Cells[1].Text.ToString().Trim());

            //int indexRow = parentRow.RowIndex;

I have tried various methods such as using hidden fields and evaluating variables in the gridview template field, but none have yielded the desired results so far. As the expand/collapse functionality is handled using JavaScript, I am struggling to access the parent gridview through conventional methods like _IndexChanged or _RowCommand.

To make debugging easier, I included the code snippet in the _RowEditing method, even though I am aware that e pertains to the child gridview. The commented out lines are attempts that either failed or retrieved the current row of the child gridview.

Admittedly, I am relatively new to C# programming, and I suspect that I may be overlooking something obvious. However, despite my best efforts, I have been unable to pinpoint the issue.

Answer №1

Perhaps this method could be the solution you are seeking: By utilizing the RowDataBound event, you have the ability to interact with each row on the server-side:

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if(e.Row.RowType==DataControlRowType.DataRow)
        {
            ((Label)e.Row.FindControl("myLabelId")).Attributes.Add("data-customAttribute", ((Order)e.Row.DataItem).OrderNo);
        }
    }

This method enables you to add a Label (or any other control) to a TemplatedField (e.g. with the ID of myLabelId), allowing you to add HTML attributes to that label or make any necessary changes based on your data. In the provided example, a data-customAttribute is added to the control. You can even add an onclick attribute to differentiate the current row. By accessing the data from e.Row.DataItem and casting it to your data object (e.g. Order), you can make further modifications.

Using JQuery, you can also access the label on the client-side:

// get all rows in the table, including the header
var $rows=$('#<%=gvOrders.ClientID%>').find('tr');

// access the innerHTML of the Label control we previously created, which contains the OrderNo
var OrderNo=$(aRow).find('#myLabelId').html();

It is important to note that the ClientID function returns the HTML ID of any server control, allowing you to access it using document.getElementById or $('#id').

Hopefully, these tips will prove to be helpful in your scenario.

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

Issue: Unable to locate dependencies for modules Vite and react

Struggling to develop a react app using vite and encountering the following error message: Error: Failed to scan for dependencies from entries: C:/Users/User/Desktop/responsive-app/index.html The path to my project, I am using windows for this specific p ...

Automate CSS slideshow playback using JavaScript

Using only CSS, I created a basic slideshow where the margin of the element changes upon radio button click to display the desired slide. You can view the functionality in the code snippet below. Additionally, I implemented auto play for this slideshow usi ...

New column is dynamically inserted on the far right side of the gridview

Check out my code snippet below. hitechLatestEntities db = new hitechLatestEntities(); GridView1.DataSource = db.HEADs; TemplateField tfObject = new TemplateField(); tfObject.HeaderText = "Sub-Heads Details"; tfObject.ItemTemplate = new WebForm1(ListIt ...

What is the best way to adjust the size of a div element so that it is

I am facing an issue with a table that contains a TreeView within a cell. The code snippet is shown below: <style> #leftPanel { width:60px; height:'100%'; border:1px solid red; ...

Exploring Objects without the need for loops

Currently, I am focusing on optimizing the performance of the following objects: var scheduleFee = { poor = {level1:25,level2:25,level3:25} , good = {level1:15,level2:20,level3:25} , vgood = {level1:10,le ...

Comparing timestamps in JavaScript and PHP - what are the discrepancies?

I seem to be having an issue with the inconsistency in count between two timestamps. Upon page load, I set the input value as follows: $test_start.val(new Date().getTime()); //e.g. equal to 1424157813 Upon submitting the form via ajax, the PHP handler sc ...

What is the best way to filter out empty arrays when executing a multiple get request in MongoDB containing a mix of strings and numbers?

I am currently working on a solution that involves the following code: export const ProductsByFilter = async (req, res) => { const {a, b, c} = req.query let query = {} if (a) { query.a = a; } if (b) { query.b = b; } if (c) { ...

What is the best way to create a layout with two images positioned in the center?

Is it possible to align the two pictures to the center of the page horizontally using only HTML and CSS? I've tried using this code but it doesn't seem to work: #product .container { display: flex; justify-content: space-between; flex-w ...

How can Selenium ChromeDriver be used to retrieve saved extension configurations?

In my current setup, I am utilizing Selenium.WebDriver.ChromeDriver version 2.38.0 paired with Chrome version 66.0.3359.117 (official build). To further elaborate on this topic, let's consider an example extension. For the purpose of this discussion, ...

File not found: The specified file 'C:Self Project eact-shopper eact-shopperclientuildindex.html' does not exist

I followed the tutorial and startup code by Reed Barger exactly, but every time I try to run the server I encounter this error: Error: ENOENT: no such file or directory, stat 'C:\Self Project\react-shopper\react-shopper\client&bso ...

What could be causing the delay in response times from these unpredictable APIs within the Express server?

We are currently experiencing performance issues with our Express.js server and MongoDB database. Randomly, some API requests are taking too long to respond or timing out throughout the day. Our application is in production, hosted on two AWS instances wit ...

Why is TypeScript giving an error about an undefined object key, even though the key was assigned a value in the previous command?

type MaybeThereIsAValue = { [p: string]: string | undefined } ... let bar: MaybeThereIsAValue = {}; const key = "carpe"; bar[key] = "diem"; const why = bar[key]; // why is string | undefined I am confused as to why why is showing ...

Check the similarity between two lists and update the status of one if they have a match

Within my MVC framework, I am working with a list of 30 bookings, each initially set with a default status of available. public class Day { public int dayNumber; public Status status; } public enum Status { available, booked, closed } List& ...

exchange the class using only JavaScript

I need help with a code snippet that allows for swapping classes using a loop. The objective is to click on the brown square causing it to move to the position of the blue square, while the blue square moves to the previous position of the brown square. T ...

I'm curious as to why styled components weren't working before

I'm attempting to utilize the before on styled components in React, but it doesn't seem to be functioning correctly. Prior to adding before, the background image was displayed, but after its inclusion, the image is no longer showing up; import st ...

What causes these queries to function separately but fail when combined?

I am facing an issue with combining 2 queries in my Firestore collection. These are the 2 examples that work: database .collection('servicebonnen') .where('medewerker', '==', 'CEES') and: database .collecti ...

Two values are returned from the Node.js Mongoose Exports function

Currently, I am encountering an issue with my project where a service I developed is up and running. However, it is not providing the desired value as a response. Specifically, the goal is to generate coffee items linked to specific companies. Whenever new ...

Using recursive setTimeout in Javascript may not always utilize the entire final JSON object that is returned

My current approach involves making recursive calls to a URL until it returns either a success or reaches the maximum limit of tries. Below is a compact version of the relevant code: function doSomething(numRetries) { $.post('someURL', {retr ...

What is the reason behind the C# button_clicked function not triggering the Javascript function?

When the user clicks the button, I want to test the C# code side. The method in the C# function should call a JavaScript function to display an alert with the results of a C# public variable. However, it seems that nothing is being called at all. At the bo ...

Tallying the number of messages on Facebook

Greetings everyone! I have been utilizing the Facebook JS SDK to retrieve the number of messages sent. Below is the code snippet: <script> function statusChangeCallback(response) { console.log('statusChangeCallback'); console.log ...