Solved

How do I add gridview rows dynamically?

Posted on 2011-02-28
14
526 Views
Last Modified: 2012-05-11
I found examples of how to do this, but it doesn't work in Firefox.

I want to populate a gridview when the page loads.  Then have users dynamically add N number of rows of text boxes for data entry and then on the save button loop through and add them all at once.  If I do it one at a time it will be time consuming fast.  Also, there is no guarantee that the master record has a PK yet (new record).

I don't usually ask this, but If you have code, I'd appreciate it. I got slammed with this on Friday night and need to get it out pronto as it's a registration system for an event that opens in 3 weeks, so I need it out the door this week.  I can do the backend C#  looping and adding bit, I just need the javascript code for a button to add the rows to the gridview with an ASP text box and a required field validator and a delete button for deleting the row if they want.  

I'm on VS2005 if that matters.  :(

500 points for being in a hurry and asking for code.  Thanks folks, appreciate it.
0
Comment
Question by:dtburdick
  • 8
  • 6
14 Comments
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
If we could start from your current template, this would be greatly appreciated to deliver quickly what you want :)
0
 

Author Comment

by:dtburdick
Comment Utility
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="Matchmaking_test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>

<script type="text/javascript">

            function fn_AddFilterRow()
            {
        // 1. Get the <table> element corresponding to the gridview from the document
            var table = document.getElementById('myGridView');
 
 
 
        // This is what dies in FF.  No errors, just doesn't work.
         
        // 2. Insert a new row in the table fetched in step 1.
               var newRow = table.insertRow();

// Tried this: var newRow = document.getElementById('myGridView').insertRow();


        // 3. Insert an empty cell for the first "Modify" column
                // Column 1 : An empty cell for the "Modify" column\\

                var btnDelete = document.createElement("<input type='button' value='Delete'>");
               
                btnDelete.type = 'button';
                var newCell = newRow.insertCell();
                newCell.appendChild(btnDelete);


        // 4. Insert an empty cell for "WorkOrderID" in the row created in step 2. above.                                    
                // Column 1 : WorkOrderID
                newCell = newRow.insertCell();
        // In the cell created above, add a textbox in which the user will input the  workorderID value he wishes to insert.
            var newTextBox = document.createElement('input');
            newTextBox.type = 'text';
            newCell.appendChild(newTextBox);
   
        // 5. Insert an empty cell for ProductID in the row created above.
                // Column 2 : ProductID
                newCell = newRow.insertCell();
        // In the cell created above, add a textbox in which the user will input the ProductID value he wishes to insert.
            var newTextBox = document.createElement('input');
            newTextBox.type = 'text';
            newCell.appendChild(newTextBox);

        // 6. Insert an empty cell for OrderQty in the row created above.                                
                // Column3 : OrderQty
                newCell = newRow.insertCell();
        // In the cell created above, add a textbox in which the user will input the OrderQty value he wishes to insert.
            var newTextBox = document.createElement('input');
            newTextBox.type = 'text';
            newCell.appendChild(newTextBox);

        // Do the same for the remaining columns.

        }

</script>
   
   
</head>
<body>
    <form id="form1" runat="server">
    <input type="button" id="btnAddRow" value="Add" runat="server" />
    <div>
        <asp:GridView ID="myGridView" runat="server" >
            <Columns>
                <asp:TemplateField>
                    <HeaderTemplate>
                        Modify
                    </HeaderTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>

</body>
</html>
0
 

Author Comment

by:dtburdick
Comment Utility
This is a two-part series on how to do it.  Doesn't include the creation of the .NET server side-controls.  I figured someone has done this and would have the basics I could fill in.  I'm not a newby, but I don't do this stuff too often, so I always fee like I'm starting from scratch.

Thanks!
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
Put the following in the head section of your page :


<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        $("#<%= btnAddRow.ClientID %>").click(function() {
            var modifyAndWorkOrderIDCell = "<td><input type='button' value='Delete' /><input type='text' /></td>";
            var ProductIDCell = "<td><input type='text' /></td>";
            var OrderQtyCell = "<td><input type='text' /></td>";
            $("tbody", "#<%= myGridView.ClientID %>").append("<tr>" + modifyAndWorkOrderIDCell + ProductIDCell + OrderQtyCell + "</tr>");
        });
    });
</script>

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
handle the delete button :

$("input[type='button'][value='Delete']").click(function() {
     $(this).parents("tr").remove();
});

Open in new window


so :
<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        $("#<%= btnAddRow.ClientID %>").click(function() {
            var modifyAndWorkOrderIDCell = "<td><input type='button' value='Delete'><input type='text' /></td>";
            var ProductIDCell = "<td><input type='text' /></td>";
            var OrderQtyCell = "<td><input type='text' /></td>";
            $("tbody", "#<%= myGridView.ClientID %>").append("<tr>" + modifyAndWorkOrderIDCell + ProductIDCell + OrderQtyCell + "</tr>");
        });
        $("input[type='button'][value='Delete']").click(function() {
            $(this).parents("tr").remove();
        });
    });
</script>

Open in new window

0
 

Author Comment

by:dtburdick
Comment Utility
I put in in and IE errors out at the first $.
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
Sorry, you need to add jquery plugin (before the script itslef), here line 1 :
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        $("#<%= btnAddRow.ClientID %>").click(function() {
            var modifyAndWorkOrderIDCell = "<td><input type='button' value='Delete'><input type='text' /></td>";
            var ProductIDCell = "<td><input type='text' /></td>";
            var OrderQtyCell = "<td><input type='text' /></td>";
            $("tbody", "#<%= myGridView.ClientID %>").append("<tr>" + modifyAndWorkOrderIDCell + ProductIDCell + OrderQtyCell + "</tr>");
        });
        $("input[type='button'][value='Delete']").click(function() {
            $(this).parents("tr").remove();
        });
    });
</script>

Open in new window

0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 82

Expert Comment

by:leakim971
Comment Utility
0
 

Author Comment

by:dtburdick
Comment Utility
That worked for adding the row.  I still need to get the backend piece working.  Do you mind if I keep this thread open until I get that going? Thanks, BTW.
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
np prob Sir, you're the Boss ;-)
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
you may need to remove the << runat="server" >> in the << Add input button >>
0
 

Author Comment

by:dtburdick
Comment Utility
Hardly the boss.  Two days later and I want to kill myself.  lol

I have:

a) sat through a bunch of jQuery tutorials
b) created a form that allows user to add/delete rows from the table
c) submited the table to the server with the rest of my form controls (lol @ form validation)
d) created a hidden input to hold the postback values of my table values field/row delimited

Everything is copacetic, however, if the user hits the back button, all of my table values disappear and end up like they were when the page was first served.  I put in code to expire the page, but that's really ugly in this instance.

Is there a way to get the table to persist in the form it was when it was posted?  If not, this was a waste of time.

The full scenario is pretty basic:

Form 1) user logs in (or creates a login which creates a blank organization row)
Form 2) populate with existing company data (if there is any), user adds info about company
Form 3) user gets into the rest of app

My problem is in Form 2.  The user needs to add N number of contacts for their company which I need to submit to the database into a different table.  I CAN denormalize it and put Contact1, Contact2, etc., but that makes me sad.  I can also allow them to click an ASP button, but every time you do that it sends the page back to the server and doesn't scroll down correctly.  Also makes me sad.

What I was hoping to do was create a dynamic table and submit it to the server, delete all the contacts, and add them back in from the values in the table.

I realize this won't work if JS is off, but the contacts aren't absolutely necessary and I've defaulted that section to display:none.  Besides, if JS is turned off at this point the Internet is broken for them anyway.

Is there a SIMPLE (fingers lightly crossed) jquery plugin that will let me integrate with my database?  The master record is already created by the time they reach Form 2, so I have the ID for that row available.
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
Comment Utility
0
 

Author Comment

by:dtburdick
Comment Utility
Yeah, I read about that one.  It looks like the best one out there, but it also seems like too much to try to figure out in the time I have, but I will take a good look at it as I need to incorporate this functionality in the scaled up version of this application anyway.  And, it's high time I learned jquery/ajax.

You get the points because that's the right answer.  I just wish it were one I could use now.  :P

Am I correct that there is no way to recover from the fact that the (bloody hell) back button erases all changes the user made (new rows, etc.) to the previous form?

Thanks for the help by the way.  I learned a lot even if I'm not going to implement it that way.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Introduction HyperText Transfer Protocol (http://www.ietf.org/rfc/rfc2616.txt) or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to t…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now