Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Folks,
I promise to share the solution with as many people as there are interested parties 8-)! Thanks in advance.

Env.: VS 2008, .NET 3.5.

I have the following datagrid on a user control with RowNbr, LastName, FirstName, MiddleName, NameFormat and CharsLeft, in 5 rows:

XML
<asp:Panel ID="Panel1" runat="server">
    <asp:Table ID="Table1" runat="server">
        <asp:TableRow ID="TableRow1" runat="server">
            <asp:TableCell ID="TableCell1" runat="server" ColumnSpan="6">
                <asp:DataGrid runat="server" ID="dgNames" AutoGenerateColumns="False">
                    <Columns>
                        <asp:BoundColumn DataField="RowNbr" HeaderText="Row#">
                        </asp:BoundColumn>
                        <asp:TemplateColumn HeaderText="Last Name">
                            <ItemTemplate>
                                <asp:TextBox runat="server" ID="txtLastName" Columns="18" Text='<%# DataBinder.Eval(Container, "DataItem.LastName") %>'></asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateColumn>
                        <asp:TemplateColumn HeaderText="First Name">
                            <ItemTemplate>
                                <asp:TextBox runat="server" ID="txtFirstName" Columns="18" Text='<%# DataBinder.Eval(Container, "DataItem.FirstName") %>'></asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateColumn>
                        <asp:TemplateColumn HeaderText="Middle Name">
                            <ItemTemplate>
                                <asp:TextBox runat="server" ID="txtMiddleName" Columns="18" Text='<%# DataBinder.Eval(Container, "DataItem.MiddleName") %>'></asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateColumn>
                        <asp:TemplateColumn HeaderText="Name Format" ItemStyle-Wrap="false">
                            <ItemTemplate>
                                <asp:Label runat="server" ID="lblNameFormat"></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateColumn>
                        <asp:TemplateColumn HeaderText="Chars. Left" ItemStyle-Wrap="false">
                            <ItemTemplate>
                                <asp:Label runat="server" ID="lblCharsLeft"></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateColumn>
                    </Columns>
                </asp:DataGrid>
            </asp:TableCell>
        </asp:TableRow>
    </asp:Table>
</asp:Panel>


For each of the 5 rows:
1) The NameFormat column displays as LastName/FirstName/MiddleName
2) The combination of the lengths of all names has to be less than or equal to 30 characters
3) Any column (LastName/FirstName/MiddleName) can be any length for as long as the total count is less than or equal to 30
4) The CharsLeft column displays the number of characters left, subtracted from 30, e.g. 6/30 left, if the lengths of LastName/FirstName/MiddleName combined = 24

I tried to no avail:

[EDIT] Added what OP means] I mean sometimes the app. simply crashes on me, sometimes it churns for several minutes before I have to stop it and sometimes no changes are reflected on the NameFormat and CharsLeft columns at all[/EDIT]

Attempt A)
Row 1: (I repeated this for the remain ing 4 rows):
$(document).ready(function(){
    $('#<%= dgNames.ClientID%> tr:has(td)').each(function(){
        var parentGrid = document.getElementById('#<%= dgNames.ClientID %>');
        var trTableRow = parentGrid.getElementsByTagName('TR')[1];

        var tcLastName = trTableRow.getElementByTagName('TD')[1];
        var txtLastName = tcLastName.innerText;

        var tcFirstName = trTableRow.getElementByTagName('TD')[2];
        var txtFirstName = tcFirstName.innerText;

        var tcMiddleName = trTableRow.getElementByTagName('TD')[3];
        var txtMiddleName = tcMiddleName.innerText;

        var lblNameFormat = trTableRow.getElementByTagName('TD')[4];
        var lblCharsLeft = trTableRow.getElementByTagName('TD')[5];

        lblNameFormat.text(txtLastName + '/' + txtFirstName + '/' + txtMiddleName);

        var remainingChars = 30 - (txtLastName.val().length + txtFirstName.val().length + txtMiddleName.val().length);
        lblCharsLeft.text(remainingChars + '/30');
    });
});


Attempt B)
$(document).ready(function(){
    $('#<%= dgNames.ClientID%> tr:has(td)').each(function(){
        var txtLastName = document.getElementById("<%= dgNames.ClientID %>").rows[1].cells[1].innerText;
        var txtFirstName = document.getElementById("<%= dgNames.ClientID %>").rows[1].cells[2].innerText;
        var txtMiddleName = document.getElementById("<%= dgNames.ClientID %>").rows[1].cells[3].innerText;
        var lblNameFormat =  document.getElementById("<%= dgNames.ClientID %>").rows[1].cells[4];
        var lblCharsLeft =  document.getElementById("<%= dgNames.ClientID %>").rows[1].cells[5];


        lblNameFormat.text(txtLastName + '/' + txtFirstName + '/' + txtMiddleName);

        var remainingChars = 30 - (txtLastName.val().length + txtFirstName.val().length + txtMiddleName.val().length);
        lblCharsLeft.text(remainingChars + '/30');
    });
});


Attempt C)
Row 1: (I repeated this for the remaining 4 rows):
$(document).ready(function(){
    $("#<%= dgNames.ClientID %> input[id*='txtLastName']:txtLastName.ClientID]").keyup(function(){
        $("#<%= dgNames.ClientID %> input[id*='lblNameFormat']:lblNameFormat.ClientID]").text
        (
            $("#<%= dgNames.ClientID %> input[id*='txtLastName']:txtLastName.ClientID").val() + '/' +
            $("#<%= dgNames.ClientID %> input[id*='txtFirstName']:txtFirstName.ClientID]").val() + '/' +
            $("#<%= dgNames.ClientID %> input[id*='txtMiddleName']:txtMiddleName.ClientID]").val()
        );

        $("#<%= dgNames.ClientID %> input[id*='lblCharsLeft']:lblCharsLeft.ClientID]").text
        (
            $("#<%= dgNames.ClientID %> input[id*='txtLastName']:txtLastName.ClientID").val().length +
            $("#<%= dgNames.ClientID %> input[id*='txtFirstName']:txtFirstName.ClientID]").val().length +
            $("#<%= dgNames.ClientID %> input[id*='txtMiddleName']:txtMiddleName.ClientID]").val().length
        );
    });
});
Posted
Updated 18-Dec-13 3:14am
v6
Comments
CHill60 18-Dec-13 8:53am    
What do you mean by to no avail? Exactly how did the results you got differ from those you expected?
Sainey 18-Dec-13 9:08am    
I mean sometimes the app. simply crashes on me, sometimes it churns for several minutes before I have to stop it and sometimes no changes are reflected on the NameFormat and CharsLeft columns at all.
CHill60 18-Dec-13 9:15am    
I've added this detail to your post. If you have any further information to add you can use the Improve question link
Sainey 18-Dec-13 9:22am    
Thanks for the edit. I was trying to keep the length of the post short so I figured I'd concentrate on stating the problem and what I had tried so far to solve it. I am still chipping away at it.
CHill60 18-Dec-13 11:55am    
Wish I could actually help! Sorry but good luck

1 solution

XML
Here is the solution to the above.  100% of the credit goes to Rion Williams (http://forums.asp.net/members/Rion%20Williams.aspx)

<html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1"><title>

</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

    <script type="text/javascript">
        $(function () {
            //Iterate through each of the rows in your table
            $("#dgNames tr:not(:first-child)").each(function () {
                //Grab your values (using the appropriate selectors)
                var fn = $(this).find('[id*=txtLastName]').val();
                var ln = $(this).find('[id*=txtFirstName]').val();
                var mn = $(this).find('[id*=txtMiddleName]').val();

                //Total characters used
                var total = fn.length + ln.length + mn.length;

                //Grab your label and set the text
                $(this).find('[id*=lblNameFormat]').text(ln + '/' + fn + '/' + mn);

                //Get the length and display it out of 30
                $(this).find('[id*=lblCharsLeft]').text(total.toString() + '/30');
            });

          //Whenever an input element is changed in the table, update everything
          $("#dgNames input").change(function(){
               var $row = $(this).closest('tr');

               //Grab your values (using the appropriate selectors)
                var fn = $row.find('[id*=txtLastName]').val();
                var ln = $row.find('[id*=txtFirstName]').val();
                var mn = $row.find('[id*=txtMiddleName]').val();

                //Total characters used
                var total = fn.length + ln.length + mn.length;

                //Grab your label and set the text
                $row.find('[id*=lblNameFormat]').text(ln + '/' + fn + '/' + mn);

                //Get the length and display it out of 30
                $row.find('[id*=lblCharsLeft]').text(total.toString() + '/30');
          });

          //Whenever an input element is changed in the table, update everything
          $("#dgNames input").keypress(function(){
               var $row = $(this).closest('tr');

               //Grab your values (using the appropriate selectors)
                var fn = $row.find('[id*=txtLastName]').val();
                var ln = $row.find('[id*=txtFirstName]').val();
                var mn = $row.find('[id*=txtMiddleName]').val();

                //Total characters used
                var total = fn.length + ln.length + mn.length;

                //Grab your label and set the text
                $row.find('[id*=lblNameFormat]').text(ln + '/' + fn + '/' + mn);

                //Get the length and display it out of 30
                $row.find('[id*=lblCharsLeft]').text(total.toString() + '/30');
          });
        });
    </script>
</head>
<body>
    <form method="post" action="WebForm1.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="kvlNwX7CWFGhLpqsuiBFr2cHrUWnKuPZPo6PQgeOZ/0ai4je/kwg66XNP40MV68bO0nt2yKA0v+Z+BqM8gg4LPLFLUpxrfr/ZTgEG7ejm4CUT+5khw63pD8k3guTh/hn6gl4zjTMcalLubciHMC8KR7aJXDOCN4NvstrZbnRGSKGBSYAx090KXin03PhwNOmu/YA8TP4ur7KLYBgjfhqBF4oEUunJW0d/cdhARerSRinYGwyx5fkcrGNdmzKbcwWO4s/6yOq5pDsslNTMqvB5NnNxKVt6POTAOMngqzAmdEw4iRMf61ChV4j5V0ftdxB">
</div>

<div class="aspNetHidden">

    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="M8XasNVNVfJ6leB6HSOkTyYKrIgeL/Fjp+Azojc7K5+17tRIyrPlAY45wrBBP7m0fKz/DC6Z5IBScNxj6/zuYMi6At3Mcw8TaxJEYF1g6yWSAZW/vsX5R0h6zUZyz9rsYWjJSJzhYRsLWSB/y30ETd57SekugbQCGjU8eT47soa8pj71RmyIfEQbwWXtB7b+T+W/wx6vAyg/AB5MgspNzwpworTpwMAL4H2S3u+0vqQMQ7+/PKzhRwp6thqa+CvfpGJ2xApFOqbb3Qt1MjFWihonHSldJQFZhhSjvbXtcy0=">
</div>
        <div id="Panel1">

    <table id="Table1">
        <tbody><tr id="TableRow1">
            <td id="TableCell1" colspan="6"><table cellspacing="0" rules="all" border="1" id="dgNames" style="border-collapse:collapse;">
                <tbody><tr>
                    <td>Row#</td><td>Last Name</td><td>First Name</td><td>Middle Name</td><td>Name Format</td><td>Chars. Left</td>
                </tr><tr>
                    <td>1</td><td>
                                <input name="dgNames$ctl02$txtLastName" type="text" value="DOE" size="18" id="dgNames_txtLastName_0">
                            </td><td>
                                <input name="dgNames$ctl02$txtFirstName" type="text" value="JOHN" size="18" id="dgNames_txtFirstName_0">
                            </td><td>
                                <input name="dgNames$ctl02$txtMiddleName" type="text" value="JOHN" size="18" id="dgNames_txtMiddleName_0">
                            </td><td style="white-space:nowrap;">
                                <span id="dgNames_lblNameFormat_0">JOHN/DOE/JOHN</span>
                            </td><td style="white-space:nowrap;">
                                <span id="dgNames_lblCharsLeft_0">11/30</span>
                            </td>
                </tr><tr>
                    <td>2</td><td>
                                <input name="dgNames$ctl03$txtLastName" type="text" value="DOE" size="18" id="dgNames_txtLastName_1">
                            </td><td>
                                <input name="dgNames$ctl03$txtFirstName" type="text" value="JOHN" size="18" id="dgNames_txtFirstName_1">
                            </td><td>
                                <input name="dgNames$ctl03$txtMiddleName" type="text" value="NMN" size="18" id="dgNames_txtMiddleName_1">
                            </td><td style="white-space:nowrap;">
                                <span id="dgNames_lblNameFormat_1">JOHN/DOE/NMN</span>
                            </td><td style="white-space:nowrap;">
                                <span id="dgNames_lblCharsLeft_1">10/30</span>
                            </td>
                </tr><tr>
                    <td>3</td><td>
                                <input name="dgNames$ctl04$txtLastName" type="text" value="GANT" size="18" id="dgNames_txtLastName_2">
                            </td><td>
                                <input name="dgNames$ctl04$txtFirstName" type="text" value="RONALD" size="18" id="dgNames_txtFirstName_2">
                            </td><td>
                                <input name="dgNames$ctl04$txtMiddleName" type="text" value="NM" size="18" id="dgNames_txtMiddleName_2">
                            </td><td style="white-space:nowrap;">
                                <span id="dgNames_lblNameFormat_2">RONALD/GANT/NM</span>
                            </td><td style="white-space:nowrap;">
                                <span id="dgNames_lblCharsLeft_2">12/30</span>
                            </td>
                </tr>
            </tbody></table></td>
        </tr>
    </tbody></table>

</div>
    </form>


</body></html>


*******************
My minor updates to Rion's solution for my particular scenario...
*******************

<style type="text/css">
.negativeNumbers
{
    background-color: #FF99AA;
}
</style>

$(function () {
    //Iterate through each of the rows in your table
    $("#dgNames tr:not(:first-child)").each(function () {
        //Grab your values (using the appropriate selectors)
        var ln = $(this).find('[id*=txtLastName]').val();
        var fn = $(this).find('[id*=txtFirstName]').val();
        var mn = $(this).find('[id*=txtMiddleName]').val();

        //Total characters used
        var total = ln.length + fn.length + mn.length;

        //Grab your label and set the text
        $(this).find('[id*=lblNameFormat]').text(total + '/' + fn + '/' + mn);

        //Get the length and display it out of 30
        $(this).find('[id*=lblCharsLeft]').text('(' + total.toString() + '/30)');
    });

    //Whenever an input element is changed in the table, update everything
    $('#<%= dgNames.ClientID %> input').keyup(function(){
        var $row = $(this).closest('tr');

        //Grab your values (using the appropriate selectors)
        var ln = $row.find('[id*=txtLastName]').val();
        var fn = $row.find('[id*= txtFirstName]').val();
        var mn = $row.find('[id*= txtMiddleName]').val();
        var aliasSuffix = $row.find('[id*= txtAliasSuffix]').val();

        //Total characters used...max = 30, subtract 3 for the slashes.
        var total = ln.length + fn.length + mn.length;
        var charsLeft = 30 - total - 3;

        //Grab your label and set the text
        $row.find('[id*=lblNameFormat]').text(ln + '/' + fn + '/' + mn);

        //Get the length and display it out of 30
        $row.find('[id*=lblCharsLeft]').text('(' + charsLeft.toString() + '/30)');

        if(charsLeft < 0)
        {
            $row.find('[id*=lblCharsLeft]').addClass('negativeNumbers');
        }
        else
        {
            $row.find('[id*=lblCharsLeft]').removeClass('negativeNumbers');
        }
    });
});
 
Share this answer
 
Comments
CHill60 18-Dec-13 19:10pm    
My 5 for persisting to find the solution ... and as you say, this might help someone else
Sainey 18-Dec-13 21:53pm    
Thank you kindly. It was an unusual grid formatting request but it's been a good learning experience, so I will definitely save this code!
CHill60 19-Dec-13 8:18am    
Check out the bookmarking feature here ... star in top right corner next to your original post
Sainey 19-Dec-13 8:42am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900